c++ - 字符串文字唯一性要求

标签 c++

我一直明白字符串文字的存储是实现定义的,因此编译器可以自由地汇总多个文字,这样,给定

static const char* foo = "blah";
static const char* bar = "blah";

foo 和 bar 可以指向同一个内存。但是,我不知道在以下情况下这是否也成立:

static const char foo[] = "blah";
static const char bar[] = "blah";

最佳答案

格式良好的程序无法判断 fooblah 是否存储在同一地址,因此我相信优化器可以将常量折叠在一起。

[expr.rel](草案 3225)说:

If two pointers p and q 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 is null, the results of p<q, p>q, p<=q, and p>=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/

相关文章:

C++从文件中读取数据到char *

c++ - 复合表达式与表达式与子表达式

c++ - 该表达式在 C++ 中意味着什么

c++ - 仅使用 volatile 修复 DCLP

php multi exec 很慢(19 分钟?)

c++ - Windows 上使用 C++ 的异步对话框

C++ 重载 + 运算符只有成员函数用于添加带有整数的类对象

c++ - 传递失败的模板参数

c++ - 如何使用 openMP 并行化内部循环?

c++ - 在 C++ 中创建类型未知的模板 vector (空模板)