Boost logo

Boost :

Subject: Re: [boost] Improving the assignment operators of various Boosttypes
From: David Abrahams (dave_at_[hidden])
Date: 2008-09-11 09:59:48


on Thu Sep 11 2008, Gevorg Voskanyan <v_gevorg-AT-yahoo.com> wrote:

> David Abrahams wrote:
>
>> on Wed Sep 10 2008, "Scott McMurray" wrote:
>>
>> > On Wed, Sep 10, 2008 at 21:23, Joe Gottman wrote:
>> >> Joel Falcou wrote:
>> >>>
>> >>> I may come late and maybe like an unwanted guest in this discussion but I
>> >>> am curious to know how i can know that for a given class of mine, the swap
>> >>> value operator= is better than the by const ref operator= ?
>> >>>
>> >>
>> >> My rule of thumb is that if your assignment operator might throw an
>> >> exception and you want assignment to fulfill the strong exception safety
>> >> guarantee (i.e. either the assignment succeeds or the target remains
>> >> unchanged) then you should consider the swapping operator=.
>> >>
>> >
>> > I would even go slightly more expansive than that and say "Use the
>> > swapping operator= unless you've explicitly decided you want less
>> > exception safety (like for efficiency reasons in std::vector)".
>> >
>> > It means one fewer place that needs updating when members change, and
>> > I suspect -- though I have no supporting data -- that the optimizer
>> > should make the swapping version "good enough" in most cases.
>>
>> Swapping and taking the parameter by value are orthogonal issues; the
>> latter has only to do with copy elision and not with exception safety.
>> Please see this thread:
>>
> http://groups.google.com/group/comp.lang.c++.moderated/browse_frm/thread/97ad5390e34d63a9/ef6b55d24b512070
>
> AFAIU, a swapping assignment operator taking the parameter by const ref adheres
> to the strong exception safety guarantee, whereas the one taking the parameter
> by value fulfills the nothrow guarantee. Not sure how practical and/or relevant
> the difference in this context is, though.
>
> Is my observation above correct?

Well, technically, yeah... although the expression that does the
assignment can still throw, so I don't think it makes much difference to
say that it's nothrow. In other words, if I give you

    f(std::string); // nothrow
    g(std::string&); // strong guarantee

For all practical purposes, you know that f and g have equivalent
exception behavior because std::string's copy ctor can throw.
      
I think this calculus might get more interesting when rvalue references
are involved, because you can actually write stronger conditional
guarantees.

-- 
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