传递给std :: runtime_error的ctor的字符串对象的生命周期是多少?

xml*_*lmx 0 c++ standards exception object-lifetime c++11

根据cppreferences,explicit runtime_error( const std::string& what_arg );不会复制what_arg的内容.

我可以安全地将临时字符串对象传递给std::runtime_error's ctor

例如:

std::string GetATempString(const char* msg)
{
    return { msg };
}

int main()
{
    try {
        throw std::runtime_error(GetATempString("Hello"));
    } catch (const std::runtime_error& e) 
    {
            e.what(); // Is it guaranteed that "Hello" would be returned safely?
    }
}
Run Code Online (Sandbox Code Playgroud)

Yak*_*ont 5

你误会了. std::runtime_error始终将字符串复制到引用计数的写时复制内部缓冲区,因为它可能在以后复制时不会引发异常.