常量字符串地址 [英] Constant strings address
问题描述
我的程序中有几个相同的字符串常量:
I have several identical string constants in my program:
const char* Ok()
{
return "Ok";
}
int main()
{
const char* ok = "Ok";
}
是否保证它们具有相同的地址,即我可以写以下代码?我听说GNU C ++优化了字符串,因此它们具有相同的地址,我可以在程序中使用该功能吗?
Is there guarantee that they are have the same address, i.e. could I write the following code? I heard that GNU C++ optimize strings so they have the same address, could I use that feature in my programs?
int main()
{
const char* ok = "Ok";
if ( ok == Ok() ) // is it ok?
;
}
推荐答案
当然不能保证,但是
C ++标准说(2.13.4 / 2字符串文字):
The C++ standard says (2.13.4/2 "String literals):
是否所有字符串文字都是唯一的(即存储在不重叠的对象中)是实现定义的。
Whether all string literals are distinct (that is, are stored in nonoverlapping objects) is implementation-defined.
要清楚,您不应该编写假定会进行此优化的代码-就像Chris Lutz所说的那样,依赖于此的C ++代码就是等待被破坏的代码。
To be clear, you shouldn't write code that assumes this optimization will take place - as Chris Lutz says, C++ code that relies on this is code that's waiting to be broken.
这篇关于常量字符串地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!