Skip to content

Latest commit

 

History

History

rvalue-references-and-move-semantics

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

Rvalue references and move semantics

Lifetime of Temporary objects

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`
    // ...
}

Best practice for pass-by-value or pass-by-const-reference

  • 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 from std::*_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?.

Pass an std::function by const-reference or by value

Put simply,

  • pass std::function by value if want to take ownership of it and it's movable. Move it again with std::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?.

References