When should I use forward and move?

后端 未结 4 1798
长情又很酷
长情又很酷 2021-02-05 12:07

I have a code that operates on a vector:

template
void doVector(vector& v, T&& value) {
    //....
    v.push_back(value);         


        
4条回答
  •  后悔当初
    2021-02-05 12:22

    • When passing a parameter that's a forwarding reference, always use std::forward.
    • When passing a parameter that's an r-value, use std::move.

    E.g.

    template 
    void funcA(T&& t) {
        funcC(std::forward(t)); // T is deduced and therefore T&& means forward-ref.
    }
    
    void funcB(Foo&& f) {
        funcC(std::move(f)); // f is r-value, use move.
    }
    

    Here's an excellent video by Scott Meyers explaining forwarding references (which he calls universal references) and when to use perfect forwarding and/or std::move:

    C++ and Beyond 2012: Scott Meyers - Universal References in C++11

    Also see this related question for more info about using std::forward: Advantages of using forward

提交回复
热议问题