简体   繁体   中英

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 eg 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.

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).

There is not necessarily an embedded std::string . The what member function is virtual, ie 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 ).

While runtime_error does take a std::string as a parameter, so it could hold on to it and return it as you suggest, the what() method is inherited from std::exception, so is more general.

The overhead of throwing an exception is likely to be high already, with stack unwinding, so you should not be worrying about this little extra bit of overhead.

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