Object construction...

B

barcaroller

At which point is an object considered to be completely constructed?

X::X()
{
// constructor stuff

throw "Exception"; // premature exit
}

X* x;

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?
 
A

acehreli

x must be initialized; otherwise its use is undefined behavior:

X * x = NULL;
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,900
Latest member
Nell636132

Latest Threads

Top