std::move Vs std::forward

跟風遠走 提交于 2019-12-03 08:30:29

In this case:

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

}

std::forward<T>(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<T> works, but it's unnecessary.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!