std::move Vs std::forward

后端 未结 1 1115
南方客
南方客 2021-02-09 17:31

This seems to be most relavant question already asked.

Whats the difference between std::move and std::forward

But each answer is different and applies and says

1条回答
  •  粉色の甜心
    2021-02-09 18:20

    In this case:

    void push_back(T&& value)
    {
         resizeIfRequired();
         moveBackInternal(std::forward(value));  // (1)             
         moveBackInternal(std::move(value));        // (2) 
    
    }
    

    std::forward(value) and std::move(value) are identical in this scenario (it doesn't matter between (1) and (2)... so use (2)).

    move is an unconditional cast to xvalue. That line gives you an expression of type T&& that's an rvalue, always.

    forward is a conditional cast. If T is an lvalue reference type, it yields an lvalue. Otherwise (if it's either not a reference type or an rvalue reference type), it yields an rvalue. In our case, T is not a reference type - so we get an rvalue.

    Either way, we end up at the same point - we call moveBackInternal with value cast as an rvalue. Just move() is a simpler way of getting there. forward works, but it's unnecessary.

    0 讨论(0)
提交回复
热议问题