Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do std::exception's derivatives pass the string from their constructor to its what() virtual function?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading