I'm curious as to why the std::exception::what
member function is const
?
class exception
{
public:
exception() throw() { }
virtual ~exception() throw();
/** Returns a C-style character string describing the general cause
* of the current error. */
virtual const char* what() const throw();
};
Calling the what()
member function should not modify the observable state of the exception
object.
Typically, exceptions are caught by const reference. For example,
try {
// ...
}
catch (const std::exception& ex) {
std::cout << ex.what();
}
If the what()
member function was not const-qualified, this pattern wouldn't work because you wouldn't be able to call it from within the catch block.
If you don't want to generate the string to be returned from what()
until it is called, you can materialize the string into a mutable member variable.
Because it doesn't mutate the Exception
instance.
In general, all functions that do not mutate their class instance should be declared const
, so that they can be called on const
-qualified variables.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With