|
Boost : |
Subject: Re: [boost] Improving the assignment operators of various Boosttypes
From: David Abrahams (dave_at_[hidden])
Date: 2008-09-11 10:09:36
on Thu Sep 11 2008, "Niels Dekker - mail address until 2008-12-31" <nd_mail_address_valid_until_2008-12-31-AT-xs4all.nl> wrote:
>>> BTW the swap member function offers a C++03 way to "move assign"
>>> [from] an rvalue:
>>>
>>> std::vector<int> generate_some_data(void);
>>> std::vector<int> my_data;
>>> // Move the result into my_data:
>>> generate_some_data().swap(my_data);
>>>
>
> Giovanni Piero Deretta wrote:
>> I guess this is a common idiom, I use it a lot.
>>
>> OTOH if my_data::operator=() used pass by value (which in the case of
>> standard containers is, unfortunately, not true), the member swap
>> wouldn't be necessary.
>>
>> In practice this means that, for your own classes, or you implement
>> the 'smart' operator= or you need the member swap (to swap out of
>> temporaries). You do not need both.
>
> When having a by-value argument for operator=, a compiler is /allowed/
> to do copy elision, but it's not /required/ to do do. So I'd
> recommend you to just keep swapping your rvalues (using member swap)
> if you already do so anyway :-)
The downside is that your code remains ugly even when you'll get
automatic optimization from the compiler for the clear syntax (or in
C++0x, move semantics support).
-- Dave Abrahams BoostPro Computing http://www.boostpro.com
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk