简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM