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 functionmyObj->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.
Throw an exception for the object's constructor. Note that the object's destructor will not be called, unlike operator delete
, which will be called automatically to reclaim the allocated memory.
Maybe it's better to make lightweight constructor which always succeeds, and Initialize function that makes heavy work and throws exception on error.
Edit. After some critical feedback, I found why my suggestion doesn't meet RAII requirements: "Resources are acquired during initialization, when there is no chance of them being used before they are available".
I don't change my original post, it may be helpful to have this as typical design error sample.
精彩评论