[英]std::forward vs std::move while binding lvalue to rvalue reference
is there a difference between move and forward here: 在这里前进和前进之间有什么区别:
void test(int && val)
{
val=4;
}
void main()
{
int nb;
test(std::forward<int>(nb));
test(std::move(nb));
std::cin.ignore();
}
In your specific case, no, there isn't any difference. 在您的特定情况下,没有,没有任何区别。
Detailed answer: 详细答案:
Under the hood, std::move(t)
does static_cast<typename std::remove_reference<T>::type&&>(t)
, where T
is type of t
(see §20.2.3/6). 在
static_cast<typename std::remove_reference<T>::type&&>(t)
, std::move(t)
执行static_cast<typename std::remove_reference<T>::type&&>(t)
,其中T
是t
类型(请参见§20.2.3/ 6)。 In your case, it resolves to static_cast<int&&>(nb)
. 在您的情况下,它将解析为
static_cast<int&&>(nb)
。
forward
is a little bit tricky, because it is tailored for use in templates (to allow perfect forwarding) and not as a tool to cast lvalue to rvalue reference. forward
有点棘手,因为它是为在模板中使用而设计的(允许完美转发),而不是将左值转换为右值引用的工具。
Standard library provides two overloads (one for lvalue references and the second for rvalue ones, see §20.2.3/2): 标准库提供了两种重载(一种用于左值引用,第二种用于右值引用,请参见第20.2.3 / 2节):
template <class T> T&& forward(typename remove_reference<T>::type& t) noexcept;
template <class T> T&& forward(typename remove_reference<T>::type&& t) noexcept;
Substituting int
, we get: 替换
int
,我们得到:
int&& forward(int& t) noexcept;
int&& forward(int&& t) noexcept;
And since nb
is lvalue, the first version is chosen. 由于
nb
是左值,因此选择第一个版本。 According to standard draft, the only effect of forward
is static_cast<T&&>(t)
. 根据标准草案,
forward
的唯一作用是static_cast<T&&>(t)
。 With T
being int
, we get static_cast<int&&>(nb)
, ie - we get two exactly same casts. 当
T
为int
,我们得到static_cast<int&&>(nb)
,即-我们得到两个完全相同的转换。
Now, if you want to cast lvalue to rvalue (to allow moving), please use only std::move
, which is the idiomatic way to do this conversion. 现在,如果要将左值转换为右值(以允许移动),请仅使用
std::move
,这是进行此转换的惯用方式。 std::forward
is not intended to be used this way. std::forward
不能以这种方式使用。
没有不同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.