[英]What are the scenarios where assignment from std::forward is preferable over assignment from std::move ? why?
While learning about std::exchange
on cppreference.com , I came across its "possible implementation" which is pasted below. 在cppreference.com上了解
std::exchange
时,我遇到了粘贴在下面的“可能的实现”。
template<class T, class U = T>
T exchange(T& obj, U&& new_value)
{
T old_value = std::move(obj);
obj = std::forward<U>(new_value);
return old_value;
}
It looked a bit odd to see obj = std::forward
in an assignment statement instead instead of std::move
, which I think would have the same effect. 在赋值语句中看到
obj = std::forward
而不是std::move
看起来有点奇怪,我认为这会产生相同的效果。
My understanding is that std::move
is equivalent to a static_cast
to rvalue reference type (but more expressive) and returns an xvalue always, whereas std::forward
returns the same value type it is passed. 我的理解是
std::move
等效于static_cast
到rvalue引用类型(但更具表达性),并且始终返回xvalue,而std::forward
返回所传递的相同值类型。
My question is why is std:forward
used in above snippet? 我的问题是为什么在上述代码段中使用
std:forward
? and is there an easy rule of thumb to decide when this is the better choice? 是否有一个简单的经验法则来决定何时才是更好的选择?
The fact that there's assignment is irrelevant. 有分配的事实是无关紧要的。 What distinguishes forward from move is what kind of argument they take when used inside your function:
从什么区别此举是向前自己的函数中使用时,他们采取什么样的说法 :
forward
is a forwarding reference parameter of your function. forward
参数是函数的转发参考参数。 move
is an rvalue reference parameter of your function (or more generally, anything you know to have no further aliases). move
的参数是函数的右值引用参数(或更一般而言,您知道没有其他别名的任何东西)。 If you exchange
with an lvalue, you don't want that to be moved-from! 如果与左值
exchange
,则不希望将其移出!
For example, consider: 例如,考虑:
std::vector<int> a, b;
f(std::exchange(a, b));
This effectively calls f(a)
but also performs a = b;
这有效地调用
f(a)
但也执行a = b;
. 。 It does not perform
a = std::move(b)
; 它不执行
a = std::move(b)
; b
is still usable in its original form afterwards! b
仍可按其原始形式使用!
See also this answer of mine, as well as many other related answers like What is std::move(), and when should it be used? 另请参阅我的答案以及其他许多相关答案,例如std :: move()是什么,何时使用它? , What's the difference between std::move and std::forward , and links therein.
, std :: move和std :: forward和其中的链接有什么区别 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.