Is Deriving from std::exception Safe in C++?

  • Context: C/C++ 
  • Thread starter Thread starter sbrothy
  • Start date Start date
  • Tags Tags
    C++ Classes deriving
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
4 replies · 2K views
sbrothy
Gold Member
Messages
1,800
Reaction score
1,522
I'm not a newbee to C++ but I've been out of the loop for a while.

I know it's discouraged, if not directly a no-go, to derive from STL classes. Something that has to do, if I remember correctly, with the STL classes having no virtual destructors.

It will work in the short run but may explode in your face later if you don't know exactly what you're doing.

With std::exception (and std::runtime_error), however, which does actually have virtual destructor(s) this practice should be OK though, right?

Regards.
 
Physics news on Phys.org
  • Like
Likes   Reactions: Vanadium 50 and sbrothy
I may have unintentionally muddied the waters here. I didn't mean deriving from STL classes (which I'm pretty sure is frowned upon) but from std::exception (or possibly std::runtime_error, but in my scenario I don't need the what() string that comes with the last). I want to store a std::vector (or some other STL container) inside my std::exception derivative because my custom exception needs to store a bunch of warnings or errors. It seems to be widely used and I can't really see any downsides which outweighs the potential benefits.

I can even override the ostream<< operator for easy output. For output to std::cerr and DEBUG output.

I'll post my std::exception derivative one I've cooked it up. You are welcome to shoot it down by then. :)
 
@sbrothy, I don't see any downside to this. After all, there are already several specific exception subtypes that derive from exception class. These include the classes declared in the STL <stdexception> header, including logic_error, domain_error, runtime_error, range_error, and overflow_error.
 
  • Like
Likes   Reactions: sbrothy
Good. As I pointed out I may have mixed up deriving from STL containers with deriving from std::exceptions. After all it looks like what the the std::exception is meant for. Virtual constructor and all. But as I mentioned I've been out of the look for a while so just wanted to be sure. I want to write a little C++ guide for people coming from C, so naturally I didn't want to put my foot in it right away. The way I want to derive from std::exception seems pretty "by design" and frankly I can see no better way.

I'll keep you updated...