A
Alf P. Steinbach
* Calum Grant:
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... ;-)
Typo: you meant
std::swap( x, new_x );
std::swap( y, new_y );
(std::auto_ptr has no swap member function).
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).