Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clean way to cancel object creation

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.

  • Check before new?
  • Check within constructor, returning null or something special, don't know how to handle ...
  • Check after new was successful and object is alive. Call a member function myObj->Init(). And destroy object if this fails?
like image 730
Benjamin Avatar asked Sep 29 '11 10:09

Benjamin


2 Answers

None of the above.

If the object cannot be constructed because of unmet conditions, the constructor should throw an exception with the throw statement.

like image 160
CharlesB Avatar answered Sep 22 '22 20:09

CharlesB


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 function myObj->Init(). And destroy object if this fails?

Abandoning RAII in this manner is a backwards step.

like image 40
Lightness Races in Orbit Avatar answered Sep 23 '22 20:09

Lightness Races in Orbit