为什么(仅)某些编译器对相同的字符串文字使用相同的地址?

编程入门 行业动态 更新时间:2024-10-25 04:24:13
本文介绍了为什么(仅)某些编译器对相同的字符串文字使用相同的地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

godbolt/z/cyBiWY

我可以在MSVC生成的汇编代码中看到两个'some'文字,但是只有一个带有clang和gcc.这导致代码执行的结果完全不同.

I can see two 'some' literals in assembler code generated by MSVC, but only one with clang and gcc. This leads to totally different results of code execution.

static const char *A = "some"; static const char *B = "some"; void f() { if (A == B) { throw "Hello, string merging!"; } }

谁能解释这些编译输出之间的区别和相似之处?为什么即使不要求优化,clang/gcc也会优化某些内容?这是某种不确定的行为吗?

Can anyone explain the difference and similarities between those compilation outputs? Why does clang/gcc optimize something even when no optimizations are requested? Is this some kind of undefined behaviour?

我还注意到,如果将声明更改为以下所示,则clang/gcc/msvc根本不会在汇编代码中保留任何"some".为什么行为不同?

I also notice that if I change the declarations to those shown below, clang/gcc/msvc do not leave any "some" in the assembler code at all. Why is the behaviour different?

static const char A[] = "some"; static const char B[] = "some";

推荐答案

这不是未定义的行为,而是未指定的行为.对于字符串文字,

This is not undefined behavior, but unspecified behavior. For string literals,

允许(但不是必需)编译器组合存储以相等或重叠的字符串文字.这意味着相同的字符串文字在通过指针进行比较时可能会相等,也可能会不同.

The compiler is allowed, but not required, to combine storage for equal or overlapping string literals. That means that identical string literals may or may not compare equal when compared by pointer.

这意味着A == B的结果可能是true或false,您不应依赖它们.

That means the result of A == B might be true or false, on which you shouldn't depend.

根据标准 [lex.string]/16 :

所有字符串文字是否都是不同的(即存储在非重叠对象中),以及字符串字面量的连续求值是产生相同对象还是不同对象都不确定.

Whether all string literals are distinct (that is, are stored in nonoverlapping objects) and whether successive evaluations of a string-literal yield the same or a different object is unspecified.

更多推荐

为什么(仅)某些编译器对相同的字符串文字使用相同的地址?

本文发布于:2023-11-06 09:50:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1563360.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:编译器   字符串   文字   地址

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!