Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does std::runtime_error::what() return const char* instead of std::string const&

Why does std::runtime_error::what() return const char* instead of std::string const& ? In many cases a direct return of a reference to the embedded string would be handy and it could avoid some overhead. So what is the rationale for not returning e.g. a const reference to the internal string in the first place and not offering an overloaded function ? I guess it goes along with a string ctor being able to throw an exception as well but I do not see the risk of returning a string reference.

like image 725
Martin Avatar asked Feb 02 '26 12:02

Martin


2 Answers

std::runtime_error inherits from std::exception which defines virtual const char* what() const throw(); so the simplest response is that it's an overload of the function and that you can be sure that any standard exception defines it in such way. It may (depending on the implementation) be possible to return the std::string, but it would be inconsistent with the rest of standard library.

I think the reason why the what() returns const char* is that you can avoid any operation that can possibly fail (especially that can throw exception). Consider the following code, which shouldn't fail

virtual const char* what() const throw() {
    return "An error has occured";
}

However in the following code the allocation of std::string may fail, throwing an exception:

std::string what() const throw() {
    return std::string("An error has occured");
}

If the string's constructor threw here, the application would most likely crash no matter what, because the function specifies throw().

Using std::string inside an exception introduce the need to allocate memory which may not be possible (note that std::bad_alloc inherits from std::exception too).

like image 80
stativ Avatar answered Feb 05 '26 01:02

stativ


There is not necessarily an embedded std::string. The what member function is virtual, i.e. it's designed to be overridden. The chief reason for overriding it is to provide the string in some other way than via the mechanism used by std::runtime_error (whatever that mechanism is, most probably a stored std::string).

like image 31
Cheers and hth. - Alf Avatar answered Feb 05 '26 00:02

Cheers and hth. - Alf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!