JiiPee <
kerrttuPo...@gmail.com> wrote:
> In a class when defining an assignment operator:
>
> operator=(const Obj& other)
>
> , if one uses the Copy-and-swap idiom to copy @other to this:
>
> Obj copy(other);
> copy.swap(*this);
>
> , this is obviously really good looking and elegant etc. But just
> wondering how much slower it would be than a straight/old (not so
> elegant/risky):
>
> this->a = other.a;
> this->b = other.b;
> ...
It depends on the situation.
For example, suppose you are assigning one (object similar to) std::string
to another: If the target already has enough capacity to contain the
source string, then no new allocations will be needed and it's just
a simple straightforward string copy. If the copy-and-swap idiom had
been used here, a new dynamic memory allocation would have been done
and the existing one would have been deleted, for no good reason.
The difference becomes even more drastic with classes like std::list
(or any class with a similar functionality): If the target already
has elements in it, then assigning can just assign the source elements
onto the existing target elements, thus avoiding unneeded extra
allocations. The copy-and-swap idiom would make dynamic allocations
for every single element to be copied, and then delete the existing
ones, for no reason.
Of course in other situations it doesn't really make much of a
difference.