Re: C++ FAQ Lite 12.3
* Victor Bazarov:
Alf P. Steinbach wrote:
* stf:
http://www.parashift.com/c++-faq-lite/assignment-operators.html#faq-12.3
Fred& Fred::operator= (const Fred& f)
{
// This code gracefully (albeit implicitly) handles self assignment
Wilma* tmp = new Wilma(*f.p_); // It would be OK if an exception
got thrown here
delete p_;
p_ = tmp;
return *this;
}
What if an exception was thrown in
delete p_;
? (It could, because this statement involves calling the destructor
of Wilma, right?) Would the memory region pointed to by p_ remain
allocated? (Here I assume Wilma could be more complicated than in the
example.)
To be safe, keeping the current code structure, there should be a
try-catch block, yes.
However, destructors should simply not throw (in general).
Probably a better solution would be:
Wilma* tmp = p_;
p_ = NULL;
delete tmp;
You really don't want to modify the current object before you have
acquired the resources to construct the new state.
tmp = new Wilma(*f.p_);
p_ = tmp;
return *this;
A generally better solution is the swap idiom, expressing assignment
in terms of construction instead of the other way.
void Fred::swap( Fred& other ) throw()
{
std::swap( p_, other.p_ );
}
Fred& Fred::operator( Fred other )
Did you mean
operator=
Yes.
? And I understand that 'swap' would need a modifiable 'other' but do
you really think that making a copy (to pass by value) is a good idea?
Yes, that's what's operator= is all about, making a copy.
And here we maketh it in the simplest and safest way possible, by copy
construction from actual arg.
{
swap( other );
}
However there are cases where the swap idiom isn't necessesarily most
natural or practical or efficient.
The code above assumes that swapping is essentially cost-free, as it
is when the real state is just a pointer to something dynamically
allocated.
Perhaps you just missed the whole point... The issue is with
self-assignment. Essentially, the whole idiom of checking against
self-assignment is replaced in the FAQ case with reallocation and actual
assignment, hoping it doesn't happen often.
The swap idiom tackles self assignment just fine. ;-)
You simply wrap (hide) that
into making a copy upon calling the assignment operator, right? Wouldn't
you have to deal with the OP's 'throw' issue in the copy constructor, then?
Nope.
With a swap based assignment any exception from the destruction of the old state
happens after the assignment has completed.
That exception has to propagate no matter what one does, but the swap based
assignment doesn't leak: since the assignment has gone through it now has a safe
encapsulation of the newly allocated state, instead of leaking it.
Cheers,
- Alf