c++move-semanticsstdmove

when to use move in function calls


I am currently learning more about all the c++11/14 features and wondering when to use std::move in function calls.

I know I should not use it when returning local variables, because this breaks return value optimisation, but I do not really understand where in function calls casting to a rvalue actually helps.


Solution

  • When a function accepts an rvalue reference, you have to provide an rvalue (either by having already a prvalue, or using std::move to create an xvalue). E.g.

    void foo(std::string&& s);
    
    std::string s;
    
    foo(s);            // Compile-time error
    foo(std::move(s)); // OK
    foo(std::string{}) // OK
    

    When a function accepts a value, you can use std::move to move-construct the function argument instead of copy-constructing. E.g.

    void bar(std::string s);
    
    std::string s;
    
    bar(s);             // Copies into `s`
    bar(std::move(s));  // Moves into `s`
    

    When a function accepts a forwarding reference, you can use std::move to allows the function to move the object further down the call stack. E.g.

    template <typename T>
    void pipe(T&& x)
    {
        sink(std::forward<T>(x));
    }
    
    std::string s;
    
    pipe(s);             // `std::forward` will do nothing
    pipe(std::move(s));  // `std::forward` will move
    pipe(std::string{}); // `std::forward` will move