Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid slicing of exception types (C++)

I am designing an exception hierarchy in C++ for my library. The "hierarchy" is 4 classes derived from std::runtime_error. I would like to avoid the slicing problem for the exception classes so made the copy constructors protected. But apparently gcc requires to call the copy constructor when throwing instances of them, so complains about the protected copy constructors. Visual C++ 8.0 compiles the same code fine. Are there any portable way to defuse the slicing problem for exception classes? Does the standard say anything about whether an implementation could/should require copy constructor of a class which is to be thrown?

like image 743
shojtsy Avatar asked Dec 06 '09 16:12

shojtsy


1 Answers

Your exception needs to have a public copy constructor. The compiler has to be able to copy it around for exception handling to work.

The solution to your problem is to always catch by reference instead:

try {
    // some code...
    throw MyException("lp0 is on fire!");
} catch (MyException const &ex) {
    // handle exception
}

(const-ness is optional, but I always put it in because there's rarely a need to modify the exception object.)

like image 105
Thomas Avatar answered Oct 30 '22 19:10

Thomas