Throwing exceptions from copy constructor

A

Alf P. Steinbach

* Calum Grant:
e.g. Here is an exception-neutral class. If allocation fails, or any of
the constructors throw, the class performs the correct clean-up.

class C
{
std::auto_ptr<X> x;
std::auto_ptr<Y> y;
public:
C(const C &c) : x(new X(*c.x)), y(new Y(*c.y))
{
}

For others who read this, a subtle point: this works because there's a
sequence point between each pair of initializer in the initialization list.
In a an ordinary function call it's generally not safe to have more than one
'new' in the arguments. One cure is then to wrap the allocations in
functions so that the compiler cannot choose to first allocate all objects'
memory and only then call the constructors.

Btw., there should really be some way to construct a C object... ;-)

C& operator=(const C &c)
{
std::auto_ptr<X> new_x(new X(*c.x));
std::auto_ptr<Y> new_y(new Y(*c.y));
x.swap(new_x);
y.swap(new_y);
return *this;
}

Typo: you meant

std::swap( x, new_x );
std::swap( y, new_y );

(std::auto_ptr has no swap member function).
 
J

John Carson

John Carson said:
The standard way to handle this is to wrap anything in class A that
needs to be cleaned up in a class of its own (say, classes B, C and
D) and then make objects of those classes (say, b, c and d) members
of A. The initialisation of b, c and d can then occur in A's
constructor (via the initialisation list). If, say, the
initialisation of d causes an exception, then b and c will have been
fully constructed (unlike the A object) and hence their destructors
will be called, even though the A object's constructor won't be. This
achieves the necessary cleanup.

Typo here:

"even though the A object's constructor won't be"

should be

"even though the A object's *destructor* won't be"
 

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

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,186
Members
46,744
Latest member
CortneyMcK

Latest Threads

Top