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.
Why does std::runtime_error::what() return const char* instead of std::string const& ? In many cases
Share
std::runtime_errorinherits fromstd::exceptionwhich definesvirtual 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 thestd::string, but it would be inconsistent with the rest of standard library.I think the reason why the
what()returnsconst char*is that you can avoid any operation that can possibly fail (especially that can throw exception). Consider the following code, which shouldn’t failHowever in the following code the allocation of
std::stringmay fail, throwing an exception:If the string’s constructor threw here, the application would most likely crash no matter what, because the function specifies
throw().Using
std::stringinside an exception introduce the need to allocate memory which may not be possible (note thatstd::bad_allocinherits fromstd::exceptiontoo).