Konvt
Konvt

Reputation: 125

Issue with exception constructor parameter type in the standard library

In the standard library, the parameter type of the exception class's constructor, such as std::runtime_error, follow this pattern:

runtime_error( const std::string& what_arg ); // (1)
runtime_error( const char* what_arg );        // (2)
runtime_error( const runtime_error& other );  // (3)

What confused me is that the (1) used const std::string& instead of std::string, which obviously results in an additional copy operation inside of the constructor.

If the parameter type were std::string, not only would it avoid an extra copy operation, but it would also be noexcept; which is a conclusion I recently realized:

If a function marked as noexcept has a parameter of a type that might throw an exception during its construction, then even if the exception is guaranteed to be thrown, it will not cause the program to terminate due to an exception.

This is confirmed by the test program.

So, why doesn’t the standard library exception constructor parameter list use std::string? Or is my understanding and conclusion, as well as the test program, incorrect even is an undefined behaviour?

Upvotes: 2

Views: 89

Answers (1)

Alan Birtles
Alan Birtles

Reputation: 36379

What confused me is that the (1) used const std::string& instead of std::string, which obviously results in an additional copy operation inside of the constructor.

I think you're assuming that std::runtime_error is implemented with a std::string member variable to store what(). This isn't necessarily the case, for example libstdc++ has a special __cow_string member type, libc++ uses a special std::__libcpp_refstring member type, MSVC uses a __std_exception_data type.

Having an overload taking std::string by value would actually introduce an extra copy for implementations that don't have a std::string member (one copy to the temporary std::string and a second to the internal format). A r-value reference overload would at least have no downside over the const reference but I guess nobody has felt this is worth the standardisation effort since r-values were added in c++11 (presumably because no implementations actually use a std::string member).

Exceptions are not generally implemented using std::string member to avoid the problems you mentioned, allocations may fail when creating exceptions (especially if the exception is being raised due to memory exhaustion) so there is generally some specialised allocator used which won't fail even if there's no general heap space available.

Upvotes: 5

Related Questions