Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terminate object creation in constructor [duplicate]

Tags:

c++

Possible Duplicate:
How to handle failure in constructor in C++?

Is there any pattern in C++ so i could terminate object creation in constructor if something fails? And so client that invoke constructor got information about failed obj creation?

like image 581
userbb Avatar asked Oct 25 '11 18:10

userbb


3 Answers

Yes, you can: throw an exception. This is pretty much the only sensible way. By choosing the appropriate exception class (either standard or your own) and supplying a good error message etc you'll be able to tell the caller what's gone wrong.

The FAQ has more details.

like image 187
NPE Avatar answered Nov 14 '22 14:11

NPE


You need to throw an exception. That is the best way to handle failing object creation.

Constructor Failures should be an Interesting read from Herb Sutter's GOTW.

Another way of doing this is that if a constructor encounters an error, set a status bit and let the user call IsOK() to see if construction actually worked.

But this is considered Obsolete.

Herb Says:

I have found the "if a constructor encounters an error, set a status bit and let the user call IsOK() to see if construction actually worked" method to be outdated, dangerous, tedious, and in no way better than throwing an exception.

like image 30
Alok Save Avatar answered Nov 14 '22 14:11

Alok Save


Throwing an exception is the usual way to handle that, however, i discourage you from the pattern of throwing exceptions in constructors.

We cannot ensure that a constructor will not throw an exception but it seems to me an anti-pattern to rely on exceptions thrown by constructors. There is a subtle difference :)

I usually prefer to deal with constructors that should not fail, and move the sensible logic that can fail in an Initialize method that can return a value or throw an exception.

It is more clean and avoid you bad headache when the code gets more complicated!

This is an example of why I blieve so: http://www.cs.technion.ac.il/~imaman/programs/throwingctor.html

Another interesting post is C++ : handle resources if constructors may throw exceptions (Reference to FAQ 17.4]

like image 32
Salvatore Previti Avatar answered Nov 14 '22 12:11

Salvatore Previti