Re: Object construction...
On May 10, 10:24 am, Andy Champ <no....@nospam.com> wrote:
barcaroller wrote:
At which point is an object considered to be completely constructed?
X::X()
{
// constructor stuff
throw "Exception"; // premature exit
}
X* x;
x must be initialized; otherwise its use is undefined behavior:
X * x = NULL;
try
{
x = new X; // is 'x' a complete object?
}
catch (...)
{
delete x; // is this valid?
}
Is it only the throw() that determines if an object has been constructed or
not?
IIRC it's considered as completely constructed when the constructor
exits (successfully).
That's correct.
In this case the delete will give undefined behaviour, because even if
I'm subtly wrong about when "construction is complete" you'll never get
to the return from the new call after which the assignment to x is made
- so x will have an undefined value.
Correct.
I get nervous about exceptions in constructors...
Yet there is only exceptions to avoid a half constructed object.
Herb Sutter's Exceptional C++ has been the book that eliminated my
nervousness in the past. The book presents a number of guidelines
which results in code that works even if exceptions are thrown.
One such guideline is to never release resources explicitly in code
(the idiom is RAII and predates Herb Sutter's book). so the original
code better be
SomeSmartPointer x(new X());
Ali