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?
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With