Constructors don't have a return type, so it's not possible to use error codes. The best way to
signal constructor failure is therefore to throw an exception. However, keep in mind that the
memory for the object itself is released, and the destructors for all sub-objects (i.e. members and
base classes) whose constructors have successfully run to completion will be called. The destructor
for the object being constructed will not be called.
For example (assume appropriate definitions):
class T
{
U u;
public:
T() { throw "Bye bye"; }
};
{
T * tptr=new T;
}
In this example, the memory allocated by operator new _will_ be released, and u's dtor will be
called.
class T2
{
U *uptr;
public:
T2() { uptr=new U; throw "Bye bye";}
~T2() { delete uptr; }
};
With this class, the memory occupied by T2 will be release, *BUT* T2's dtor will _not_ be
called, and the U object pointed to by uptr will be leaked.
signal constructor failure is therefore to throw an exception. However, keep in mind that the
memory for the object itself is released, and the destructors for all sub-objects (i.e. members and
base classes) whose constructors have successfully run to completion will be called. The destructor
for the object being constructed will not be called.
For example (assume appropriate definitions):
class T
{
U u;
public:
T() { throw "Bye bye"; }
};
{
T * tptr=new T;
}
In this example, the memory allocated by operator new _will_ be released, and u's dtor will be
called.
class T2
{
U *uptr;
public:
T2() { uptr=new U; throw "Bye bye";}
~T2() { delete uptr; }
};
With this class, the memory occupied by T2 will be release, *BUT* T2's dtor will _not_ be
called, and the U object pointed to by uptr will be leaked.
Comments
Post a Comment
https://gengwg.blogspot.com/