xmllmx
xmllmx

Reputation: 42379

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

Upvotes: 0

Views: 236

Answers (1)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275740

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.

Upvotes: 5

Related Questions