My C++ class aggregates a helper object which may throw an exception in the constructor, but my own class must not throw (my own class is used by a framework which is not prepared for exceptions being thrown by a constructor). Right now I mitigate this risk by delaying the construction of the helper object by creating the object using new so that I'm able to catch any exceptions:
struct HelperObject {
HelperObject() {
throw 0;
}
}
struct MyObject {
HelperObject *o;
MyObject() : o( 0 ) {
try {
o = new HelperObject;
} catch ( ... ) {
// ...
}
}
};
However it's a bit annoying to abuse new for this; I suddenly have to deal with a pointer for the entire code for no good reason except that it allows me to get more control over the time at which the object is constructed.
Is it possible to achieve something to this effect without usign new?
Could use smart pointer and an extra MakeHelperObject function so that exceptions are done inside HelperObject domain. This only makes MyObject code clean but exception still need to be processed during HelperObject construction:
struct HelperObject {
HelperObject() {
throw 0;
}
static HelperObject* MakeHelperObject()
{
try
{
HelperObject* p = new HelperObject();
return p;
}
catch(const SomeException& e)
{
// deal with e
}
return NULL;
}
};
struct MyObject {
std::unique_ptr<HelperObject> o;
MyObject() : o(HelperObject::MakeHelperObject())
{
}
};
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