c++ - Global const string& 对我来说很难闻,它真的安全吗?

标签 c++ string object constants anonymous

我正在查看一位同事的代码,我看到他在全局范围内定义了几个常量:

const string& SomeConstant = "This is some constant text";

就我个人而言,这对我来说很糟糕,因为引用指的是我假设是从给定 char 数组构造的“匿名”对象。

从语法上讲,它是合法的(至少在 VC++ 7 中),而且它似乎可以运行,但实际上我宁愿让他删除 &,这样它的作用就不会模棱两可了。

那么,这真的安全合法吗?我很着迷?正在构造的临时对象是否有保证的生命周期?我一直认为以这种方式使用的匿名对象在使用后会被破坏......


所以我的问题也可以推广到匿名对象的生命周期。标准是否规定了匿名对象的生命周期?它会与同一范围内的任何其他对象具有相同的生命周期吗?还是只给出表达式的生命周期?


此外,在本地执行时,其范围显然不同:

class A
{
    string _str;

public:
    A(const string& str) :
        _str(str)
    {
        cout << "Constructing A(" << _str << ")" << endl;
    }

    ~A()
    {
        cout << "Destructing A(" << _str << ")" << endl;
    }
};

void TestFun()
{
    A("Outer");
    cout << "Hi" << endl;
}

演出:

构造A(外部); 破坏A(外); 嗨

最佳答案

这是完全合法的。在程序结束之前不会被破坏。

编辑:是的,保证:

"All objects which do not have dynamic storage duration, do not have thread storage duration, and are not local have static storage duration. The storage for these objects shall last for the duration of the program (3.6.2, 3.6.3)."

-- 2008 Working Draft, Standard for Programming Language C++ ,第 3.7.1 页。 63

正如 Martin 所说,这不是全部答案。标准草案进一步说明(§ 12.2, p. 250-1):

"Temporaries of class type are created in various contexts: binding an rvalue to a reference (8.5.3) [...] Even when the creation of the temporary object is avoided (12.8), all the semantic restrictions shall be respected as if the temporary object had been created. [...] Temporary objects are destroyed as the last step in evaluating the full-expression (1.9) that (lexically) contains the point where they were created. [...] There are two contexts in which temporaries are destroyed at a different point than the end of the full-expression. [...] The second context is when a reference is bound to a temporary. The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference except as specified below."

我在 g++ 中进行了测试,如果这能让你感觉更好。 ;)

关于c++ - Global const string& 对我来说很难闻,它真的安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1028443/

相关文章:

c++ - WSARecvFrom 阻塞

c++ - 当一个函数结束时,它的局部变量会被释放吗?

java - 在特殊字符之间查找文本并替换字符串

java - 在Java中如何将字符串转换为int?

javascript - 在对象内填充 javascript 数组

java - 如何以千字节(kb)或字节为单位获取对象的大小

C++ - 字符串和 LPCWSTR 之间的转换

c++ - 如何将 boost 路径类型转换为字符串?

Java replace方法,用空字符替换

c++ - 将数据放在类声明中?