Search code examples
c++c++11exceptionstandardsobject-lifetime

What's the life time of the string object passed into std::runtime_error's ctor?


According to cppreferences, explicit runtime_error( const std::string& what_arg ); won't copy what_arg's content.

Can I safely pass a temporary string object into std::runtime_error's ctor?

For example:

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?
    }
}

Solution

  • You misunderstand. std::runtime_error always copies the string into a reference-counted copy-on-write internal buffer, because it may not throw an exception later when copying.