|
Boost : |
Subject: Re: [boost] Improving the assignment operators of various Boost types
From: Hervé Brönnimann (hervebronnimann_at_[hidden])
Date: 2008-09-09 22:44:03
On Sep 9, 2008, at 6:39 PM, Niels Dekker - mail address until
2008-12-31 wrote:
> Basically it was concluded that /if/ an assignment operator is
> implemented by means of copy-and-swap, it should preferably be done as
> follows:
>
> T& operator=(T arg)
> {
> arg.swap(*this);
> return *this;
> }
>
> And preferably /not/ as follows:
>
> T& operator=(const T & arg)
> {
> T(arg).swap(*this);
> return *this;
> }
>
>
> Kind regards,
> --
> Niels Dekker
> http://www.xs4all.nl/~nd/dekkerware
> Scientific programmer at LKEB, Leiden University Medical Center
For types that take allocators (the ones most likely to benefit from
swap) when the allocator follows the (new) scoped allocator model
(n2606): if T uses some allocator_type and if
std::allocator_propagate_on_copy_assignment<allocator_type> does not
derive from std::true_type, then the function swap will do a fast-
swap when *this and arg's allocators compare equal (e.g., swap the
pointers to data for containers), but will do a slow copy otherwise.
In this case, taking the argument by value adds an extra copy, since
it is not possible to control the allocator used by the temporary
(ideally, we would've liked to use this->get_allocator()).
But your msg is is all good: I was going to point out it didn't work
in the case described above, but your wording ("/if/ an assignment
operator is implemented by means of copy-and-swap") carefully
excludes this case, since it is not (always) a copy-and-swap:
sometimes it is just a fast swap.
So I do agree with you, but developers should probably bear the case
I describe above in mind as well...
Cheers,
-- Hervé Brönnimann hervebronnimann_at_[hidden]
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk