When should I use forward and move?

后端 未结 4 1799
长情又很酷
长情又很酷 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:25

    1. forward(value) is used if you need perfect forwarding meaning, preserving things like l-value, r-value.

    2. forwarding is very useful because it can help you avoid writing multiple overloads for functions where there are different combinations of l-val, r-val and reference arguments

    3. move(value) is actually a type of casting operator that casts an l-value to an r-value

    4. In terms of performances both avoid making extra copies of objects which is the main benefit.

    So they really do two different things


    When you say normal push_back, I'm not sure what you mean, here are the two signatures.

    void push_back( const T& value );
    void push_back( T&& value );
    

    the first one you can just pass any normal l-val, but for the second you would have to "move" an l-val or forward an r-val. Keep in mind once you move the l-val you cannot use it

    For a bonus here is a resource that seems to explain the concept of r-val-refs and other concepts associated with them very well.

    As others have suggested you could also switch to using emplace back since it actually perfect forwards the arguments to the constructor of the objects meaning you can pass it whatever you want.

提交回复
热议问题