Re: assignment operator implementation
In article <455109f2$0$30328$9b4e6d93@newsspool1.arcor-online.net>,
albrecht.fritzsche <albrecht.fritzsche@arcor.de> wrote:
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.
swap() <==> aiming at exception safe code.
What is the alternative?
c & operator=(c const & param_c)
{
if(this != ¶m_c)
{
(1) free resource for member one
(2) allocate new resource for member one
(3) assign param_c.member one's value to it
...for all members...
}
return *this;
}
otherwise a = a is a disaster.
It might be hard to guarantee that the object stays in a well-defined
state if one of those steps fail - just consider what happens if step
(2) fails and an exception was raised by new. In what state is now the
object???
In the swap() case the temporary gets destroyed and the object stays in
its old state - a well-defined one, hopefully ;-)
I assume that c does not really have a 'byte copy' assignment in
effect, since then the solution is to let the compiler do it.
Therefore there is likely to be a more efficient approach to swap of a
and b than
c d; d = a; a=b;b=d;
so providing a swap method, and a swap free function is a good idea for
efficiency since any properly written function using swap can use the
swap for c and not the generic version like three assignment swap
above.
Providing a swap method and a one line inlined free swap function,
allows for more efficient swapping as well, in your code or any other
source including the standard headers.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]