Subject: Re: [boost] rvalue ref best practices?
From: Simonson, Lucanus J (lucanus.j.simonson_at_[hidden])
Date: 2012-06-11 16:24:26
>In C++03, func_modify() would be the choice of performance-conscious programmers.
>In C++11, as we've told that "return by value is free" and the syntax is more elegant, I'm afraid everyone will write "func_factory".
>And func_factory() is less efficient when used in loops and other situations where resource reusing is essential.
If you aren't in a loop you probably don't care about performance. I know I intend to stick with pass by reference. It is very useful to clearly understand and be able to easily reason about the ownership of resources in a program. Get the ownership of the resource and the construction of your object in the same place as much as possible and apply RAII and you have the software design problem solved. Everyone who doesn't own the resources sees a reference to the object. Return by value is supposed to be easier to reason about than pass by reference, but I never had trouble reasoning about my code that passes by reference. If your func_factory() is a template then it needs to understand how to construct its output type and it can't infer its output type from the input arguments in most cases. In contrast func_modify doesn't need to know how to construct the output type and can infer it. You can solve these problems with func_factory using expression templates, but then you might just as well pass the left hand side of the assignment operator by reference when evaluating the expression template.
What the new language features do in my view isn't to change the language so that we always return by value and transfer ownership of resources around willy-nilly because it's "free", but to make it less expensive when our design intent really is to transfer ownership. Moving something from one container to another is a great example of a place where the intent really is to transfer ownership. We still pass containers by ref and use iterators. Sometimes one wants an accumulate semantic. In Sean Parent's own words reference semantics are unavoidable. We need reference semantics and we should understand where, why and how to use them and reason about them. We might as well embrace reference semantics and make sure we are good at reasoning about them.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk