c++ - 这个 `const char*` 的断言保证是真的吗?

标签 c++ arrays pointers comparison string-literals

<分区>

代码示例(vs2015编译运行):

#include<cassert>
using namespace std;
int main() {

    const char*p = "ohoh";
    const char*p1 = "ohoh";
    char p3[] = "ohoh";
    char p4[] = "ohoh";
    assert(p == p1);//OK,success,is this always true?
    assert(p3 == p4);//failed

    return 0;
}  

据我所知,字符串字面量存储在地址空间的readonly段,而const char*p = "ohoh";只是生成一个指针到那个位置。但是,编译器似乎只会生成该字符串文字的一个拷贝,因此 p==p1 为真。

这是一种优化,还是标准保证的东西?

最佳答案

不,标准不保证。根据cppref :

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.

关于c++ - 这个 `const char*` 的断言保证是真的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49752338/

相关文章:

c++ - "screwing up"赋值运算符会产生什么后果?

c++ - 接收信号时如何自动进行gdb核心转储

java - 在3个二维数组中找到相似的行

c++ - 为什么这个const char* 实际修改后不能修改呢?

c++ - C++创建对相同数据进行操作的子 vector

c++ - 如何在没有 boost::timer 的情况下以毫秒为单位计时

c++ - C++ 中的 Lua 转储

c - 在辅助函数上用字符串填充数组。为什么它会打印乱码?

C/CAPL 从另一个数组定义一个数组

c++ - 为满足方法参数而进行指针转换是一件危险的事情吗?