According to Move semantics and rvalue references in C++11, Alex Allain says that
Notice, by the way, that holding on to a const reference to a temporary object ensures that the temporary object isn't immediately destructed. This is a nice guarantee of C++.
Also, The C++ Programming Language - Fourth Edition chapter 6.4.2 Lifetimes of Objects describe the lifetime of Temporary objects that:
Temporary objects (e.g., intermediate results in a computation or an object used to hold a
value for a reference to const argument): their lifetime is determined by their use. If they
are bound to a reference, their lifetime is that of the reference; otherwise, they ‘‘live’’ until
the end of the full expression of which they are part. A full expression is an expression that
is not part of another expression. Typically, temporary objects are automatic.
It means that below codes will work well:
std::string getName () {
return "Alex";
}
{
// use lvalue-reference to remember the temporary object
const std::string& name = getName(); // OK
// do something with `name`
// ...
}
{
// use lvalue-reference to remember the temporary object
const std::string&& name = getName(); // also OK
// do something with `name`
// ...
}
- Old style
It used to be generally recommended best practice(i.e. in Scott Meyers, Effective C++) to use pass by const ref for all types, except for builtin types (char
,int
,double
, etc.), for iterators and for function objects (lambdas, classes deriving fromstd::*_function
). - New recommendation with move semantics
use pass by value if the function takes ownership of the argument, and if the object type supports efficient moving.
See discussion in Is it better in C++ to pass by value or pass by constant reference?.
Put simply,
- pass
std::function
by value if want to take ownership of it and it's movable. Move it again withstd::move()
if necessary. - pass
std::function
by const reference if only want to simply call it once.
See discussion in Is it better in C++ to pass by value or pass by constant reference? and Should I pass an std::function by const-reference?.
- https://github.com/wangyoucao577/modern-cpp/tree/master/understanding-cpp11#rvalue_reference
- The C++ Programming Language - Fourth Edition
- Move semantics and rvalue references in C++11
- Const References to Temporary Objects
- Is returning by rvalue reference more efficient?
- What's the difference between std::move and std::forward
- 谈谈 C++ 中的右值引用
- Correct usage of rvalue references as parameters
- What is move semantics?
- Is it better in C++ to pass by value or pass by constant reference?
- Can std::function be move-constructed from rvalue reference to a temporary functor object?
- How true is “Want Speed? Pass by value”
- Should I pass an std::function by const-reference?
- What is the correct way of using C++11's range-based for?