看一下这段代码:
#include <iostream>
using namespace std;
int main()
{
const char* str0 = "Watchmen";
const char* str1 = "Watchmen";
char* str2 = "Watchmen";
char* str3 = "Watchmen";
cerr << static_cast<void*>( const_cast<char*>( str0 ) ) << endl;
cerr << static_cast<void*>( const_cast<char*>( str1 ) ) << endl;
cerr << static_cast<void*>( str2 ) << endl;
cerr << static_cast<void*>( str3 ) << endl;
return 0;
}
这会产生如下输出:
0x443000
0x443000
0x443000
0x443000
这是在 Cygwin 下运行的 g++ 编译器上实现的。即使没有打开优化 (-O0
),这些指针也都指向同一位置。
编译器是否总是进行大量优化,以至于搜索所有字符串常量以查看它们是否相等?这种行为可以信赖吗?
最佳答案
它不可靠,它是一种优化,不属于任何标准。
我已将代码的相应行更改为:
const char* str0 = "Watchmen";
const char* str1 = "atchmen";
char* str2 = "tchmen";
char* str3 = "chmen";
-O0 优化级别的输出为:
0x8048830
0x8048839
0x8048841
0x8048848
但对于 -O1 来说是:
0x80487c0
0x80487c1
0x80487c2
0x80487c3
正如您所看到的,GCC (v4.1.2) 在所有后续子字符串中重用了第一个字符串。如何在内存中排列字符串常量是编译器的选择。
关于c++ - C/C++ : Optimization of pointers to string constants,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39336895/