Stop creating an object in the constructor

Possible duplicate:
How to handle a crash in a constructor in C ++?

Is there any template in C ++ so that I can stop creating an object in the constructor if something fails? And so the client calling the constructor got information about the failed creation of the object?

+4
source share
4 answers

Yes you can: throw an exception. This is almost the only reasonable way. By choosing the appropriate exception class (standard or your own) and providing a good error message, etc., you can tell the caller what happened.

Frequently asked questions contains more detailed information .

+11
source

You need to throw an exception. This is the best way to handle the creation of a failed object.

Constructor failures should be interesting to read from Herb Sutter GOTW.

Another way to do this is that if the constructor encounters an error, set the status bit and allow the user to call IsOK() to see if the construct is actually built.

But it is considered Obsolete .

The grass says:

I found that "if the constructor encounters an error, sets the status bit and allows the user to call IsOK () to see if the construct is really built," the method is deprecated, dangerous, tedious, and in no way better than throwing an exception.

+5
source

Throwing an exception is the usual way to handle this, however I dissuade you from the exception exception template in the constructors.

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

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

It is cleaner and avoids a bad headache when the code gets more complicated!

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

Another interesting C ++ post : handle resources if constructors can throw exceptions (link to FAQ 17.4)

+1
source

As aix explained, throwing from the constructor is the only reasonable option.

Alternatively, you can use the Named Constructor Hierarchy (see here and here ) and return a null pointer if the creation of a new object fails.

+1
source

Source: https://habr.com/ru/post/1258411/


All Articles