Home > Back-end >  How do std::exception's derivatives pass the string from their constructor to its what() virtua
How do std::exception's derivatives pass the string from their constructor to its what() virtua

Time:01-07

I'd like to reimplement the standard exception hierarchy.

std::exception is defined in the following way, according to the documentation:

class exception {
public:
  exception () noexcept;
  exception (const exception&) noexcept;
  exception& operator= (const exception&) noexcept;
  virtual ~exception();
  virtual const char* what() const noexcept;
}

Now, for example, std::logic_error is declared like this:

class logic_error : public exception {
public:
  explicit logic_error (const string& what_arg);
  explicit logic_error (const char* what_arg);
};

My question is, how does such an instantiation: std::logic_error("Error!") work under the hood?

The "Error!" string gets passed to logic_error (const char* what_arg), and somehow passes its value to the what() overload in the implementation, without calling it.

One way of doing this is probably copying the string and storing it somewhere (as a private member, in the base class), then throwing it in what().

I just wanted to clarify whether this is what I should do. I know that exceptions should be as lightweight as possible. I'd want to avoid storing any objects.

Is there a good way to implement this?

CodePudding user response:

Yes, they most likely store the string in a private member.

Not a plain std::string though, because copying those can throw. Probably something equivalent to std::shared_ptr<std::string>.

  •  Tags:  
  • Related