Re: assignment operator implementation
red floyd <no.spam@here.dude> writes:
dasjotre wrote:
I frequently see operator= implemented
through copy constructor + swap
struct c
{
c(c const & c) ...
void swap(c const & c) ...
c & operator=(c const & c)
{
c tmp(c);
swap(tmp);
return *this;
}
};
what is the benefit of this technique?
It seems rather wasteful.
The main one is that you are exception safe.
There's no reason to think that a version that does not use swap
should not be exception safe (the strong guarantee is not synonymous
with exception-safety). The main benefit of copy-and-swap assignment
is that provided you have a correct and working copy constructor, it's
very hard to get the assignment operator wrong. Here's an even
simpler one:
c& operator=(c x)
{
swap(x);
return *this;
}
However, copy-and-swap it is somewhat wasteful, because you don't
always need the strong guarantee.
--
Dave Abrahams
Boost Consulting
www.boost-consulting.com
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]