I'm wondering how to stop/cancel the creation of an object, risen by new()
. Maybe if some preconditions fail and the object isn't needed.
new
?null
or something special, don't know how to handle ...new
was successful and object is alive. Call a member function myObj->Init()
. And destroy object if this fails?None of the above.
If the object cannot be constructed because of unmet conditions, the constructor should throw an exception with the throw
statement.
Check before
new
?
If your preconditions can be verified outside of the object's own inner scope and if they semantically belong in the calling scope, then sure... this is great!
Check within constructor, returning null or something special, don't know how to handle ...
Check within the constructor, and throw an exception. Handle it like you handle any other exception. Best approach.
Check after
new
was successful and object is alive. Call a member functionmyObj->Init()
. And destroy object if this fails?
Abandoning RAII in this manner is a backwards step.
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