|
Boost : |
Subject: Re: [boost] rvalue ref best practices?
From: Giovanni Piero Deretta (gpderetta_at_[hidden])
Date: 2012-06-09 16:49:34
On Sat, Jun 9, 2012 at 9:21 PM, Daniel Larimer <dlarimer_at_[hidden]> wrote:
> I am trying to define my library API and have been using rvalue references and have observed some patterns that I would like to run by the community.
>
> In c++03 I would pass almost everything by const& unless it was to be modified. This results in extra copies any time a temporary is passed.
>
> In c++11 I would pass anything that I plan on 'storing' or 'consuming' by &&. This results in the most efficient code, but 'breaks' lvalue compatibility and forces me to consider having two (or more) versions of every method. Unfortunately, you get a explosion of permutations of rvalue and const& as the number of arguments increases and it makes getting function pointers much more 'ugly'.
>
> Instead of providing two (or more) overloads, one for lvalues and one for rvalue, I have decided to only provide the rvalue overload and if the user wants to pass an lvalue they wrap with std::ref(), std::cref(), std::move() or my own helper copy() which makes the copy explicit and converts the lvalue to a rvalue. (std::ref() and std::cref() could only work if the arguments are template parameters... in which case the method would probably use std::forward<>() to handle the auto-detection of move vs copy semantics.
>
As per http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/ ,
if the function is likely to consume or copy the parameter, the best
solution is to pass by value. This means you'll only need to provide a
single overload.
-- gpd
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk