Re: using swap to make assignment operator exception safe
"George" <George@discussions.microsoft.com> wrote in message
news:E09CA37A-D791-4FBB-A69C-E436D9EE1EB8@microsoft.com
The following swap technique is used to make assignment operator
exception safe (means even if there is exception, the current object
instance's state is invariant).
It used a temporary object "temp" in this sample, and assignment is
made on a to temp ar first.
Not an assignment - initialization, using the copy constructor.
Otherwise you will enter infinite recursion, repeatedly invoking
assignment operator.
Even if there is exception, the current
this object's state is not corrupted.
My question is, the pattern works only if there is no exception
thrown by swap function.
Correct.
[Code]
class A;
A& A::operator= (const A& a)
{
A temp;
temp = a; // exception may be thrown
You want
A temp = a;
Otherwise you would have infinite recursion.
swap (*this, temp);
Normally, class A would have a member swap() (doing something specific
to this class) and you would call
swap(temp);
Generic std::swap uses the class' copy constructor and assignment
operation, which again will lead to infinite recursion. For the code to
work as written, there should be a specialization of std::swap for class
A, or a non-template overload taking refererences to A as parameters.
return *this;
}
[/Code]
--
With best wishes,
Igor Tandetnik
With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925