Exception in constructor
Suppose we need to allocate some dynamic memory in the constructor… and while doing that the constructor throws a memory exception… so the stack based pointer which was referencing the heap based memory will be destroyed because of the stack unwinding… so we will have some memory which is referenced by no pointer and hence we cannot access that… so obviously its a memory leak… so, how can we handle that ??
Q: When does an object’s lifetime begin?
A: When its constructor completes successfully and returns normally. That is, control reaches the end of the constructor body or an earlier return statement.
Q: When does an object’s lifetime end?
A: When its destructor begins. That is, control reaches the beginning of the destructor body.
Exception in Constructor means that construction has failed, the object never existed, its lifetime never began. Indeed, the only way to report the failure of construction — that is, the inability to correctly build a functioning object of the given type — is to throw an exception.
Incidentally, this is why a destructor will never be called if the constructor didn’t succeed — there’s nothing to destroy. “It cannot die, for it never lived.”
So, Solution:
To avoid such a situation auto_ptr/shared_ptr should be used instead of a normal pointer.
If a constructor throws an exception, the object’s destructor is not run. It requires a smart pointer.
class Fred {
public:
typedef std::auto_ptr<Fred> Ptr;
…
};
class Scaler { public: Scaler(double factor) { if (factor == 0) { _state = 0; } else { _factor = factor; _state = 1; } } double ScaleMe(double value) { if (!_state) throw "Invalid object state."; return value / _factor; } int IsValid() { return _status; } private: double _factor; int _state; }
Throwing an exception is the best way of dealing with constructor failure. You should particularly avoid half-constructing an object and then relying on users of your class to detect construction failure by testing flag variables of some sort.
If exception is not thrown, then object is initialized in a zombie state. Such object needs to expose a flag which says whether the object is correct or not. Something like this:
Problem with this approach is on the caller side. Every user of the class would have to do an if before actually using the object. This is a call for bugs – there’s nothing simpler than forgetting to test a condition before continuing.
In case of throwing an exception from the constructor, entity which constructs the object is supposed to take care of problems immediately. Object consumers down the stream are free to assume that object is 100% operational from the mere fact that they obtained it.