问题描述
看看这段代码:
#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
),指针都指向同一个位置.
This was on the g++ compiler running under Cygwin. The pointers all point to the same location even with no optimization turned on (-O0
).
编译器是否总是优化到它搜索所有字符串常量以查看它们是否相等?可以依赖这种行为吗?
Does the compiler always optimize so much that it searches all the string constants to see if they are equal? Can this behaviour be relied on?
推荐答案
这是一种极其简单的优化,可能非常简单,以至于大多数编译器编写者甚至根本不认为它是一种优化.毕竟,将优化标志设置为最低级别并不意味着完全天真".
It's an extremely easy optimization, probably so much so that most compiler writers don't even consider it much of an optimization at all. Setting the optimization flag to the lowest level doesn't mean "Be completely naive," after all.
编译器在合并重复字符串文字方面的积极性会有所不同.他们可能会将自己限制在一个子程序中——将这四个声明放在不同的函数中而不是一个函数中,你可能会看到不同的结果.其他人可能会做一个完整的编译单元.其他人可能会依赖链接器在多个编译单元之间进行进一步的合并.
Compilers will vary in how aggressive they are at merging duplicate string literals. They might limit themselves to a single subroutine — put those four declarations in different functions instead of a single function, and you might see different results. Others might do an entire compilation unit. Others might rely on the linker to do further merging among multiple compilation units.
你不能依赖这种行为,除非你的特定编译器的文档说你可以.语言本身在这方面没有要求.我对在我自己的代码中依赖它持谨慎态度,即使可移植性不是问题,因为即使在单个供应商编译器的不同版本之间,行为也可能会发生变化.
You can't rely on this behavior, unless your particular compiler's documentation says you can. The language itself makes no demands in this regard. I'd be wary about relying on it in my own code, even if portability weren't a concern, because behavior is liable to change even between different versions of a single vendor's compiler.
这篇关于C/C++:优化指向字符串常量的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!