Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the C++ std::exception::what member const?

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();
};
like image 238
Matt Joiner Avatar asked Nov 27 '22 23:11

Matt Joiner


2 Answers

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.

like image 84
James McNellis Avatar answered Dec 18 '22 21:12

James McNellis


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.

like image 36
SLaks Avatar answered Dec 18 '22 22:12

SLaks