我一直明白字符串文字的存储是实现定义的,因此编译器可以自由地汇总多个文字,这样,给定
static const char* foo = "blah";
static const char* bar = "blah";
foo 和 bar 可以指向同一个内存。但是,我不知道在以下情况下这是否也成立:
static const char foo[] = "blah";
static const char bar[] = "blah";
最佳答案
格式良好的程序无法判断 foo
和 blah
是否存储在同一地址,因此我相信优化器可以将常量折叠在一起。
[expr.rel]
(草案 3225)说:
If two pointers
p
andq
of the same type point to different objects that are not members of the same object or elements of the same array or to different functions, or if only one of them isnull
, the results ofp<q
,p>q
,p<=q
, andp>=q
are unspecified.
[expr.eq]
说:
The
==
(equal to) and the!=
(not equal to) operators have the same semantic restrictions, conversions, and result type as the relational operators except for their lower precedence and truth-value result.
[expr.add]
说:
When two pointers to elements of the same array object are subtracted
(截图)
罢工>Unless both pointers point to elements of the same array object, or one past the last element of the array object, the behavior is undefined.
<罢工>罢工>
脚注:这肯定是错误的,但这是我对标准内容的解释。我很想看到 C++ 标准中覆盖这种语言的部分。
我想可能是这样的:
[intro.object]
说:
Two distinct objects that are neither bit-fields nor base class subobjects of zero size shall have distinct addresses.
[expr.eq]
说:
Two pointers of the same type compare equal if and only if they are both null, both point to the same function, or both represent the same address
所以总而言之,是的,你可以判断数组是否折叠,所以它们不能折叠。但大多数告诉方式都有未指定的结果,你必须直接在指针上使用 ==
或 !=
。正如 @aschelper 指出的,std::less
及其关系也将起作用。
关于c++ - 字符串文字唯一性要求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5246969/