std :: forward vs std :: move将lvalue绑定到右值引用 [英] std::forward vs std::move while binding lvalue to rvalue reference
问题描述
这里有move和forward之间的区别:
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();
}
推荐答案
,没有任何区别。
详细回答:
> std :: move(t) does static_cast< typename std :: remove_reference< T> :: type&& ,
T
是 t
的类型(见第20.2.3 / 6节)。在您的情况下,它解析为 static_cast< int&&>(nb)
。
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). In your case, it resolves to static_cast<int&&>(nb)
.
forward
是一个有点棘手,因为它是为模板使用(允许完美的转发),而不是作为一个工具来投资左值到右值引用。
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.
标准库提供了两个重载(一个用于左值引用,第二个用于右值引用,见第20.2.3节/2);
$ b
Standard library provides two overloads (one for lvalue references and the second for rvalue ones, see §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;
替换 int
,我们得到: p>
Substituting int
, we get:
int&& forward(int& t) noexcept;
int&& forward(int&& t) noexcept;
由于 nb
是lvalue,版本。根据标准草案, forward
的唯一效果是 static_cast< T&&>(t)
。以 T
为 int
,我们得到 static_cast< int&&
And since nb
is lvalue, the first version is chosen. According to standard draft, the only effect of forward
is static_cast<T&&>(t)
. With T
being int
, we get static_cast<int&&>(nb)
, i.e. - we get two exactly same casts.
现在,如果要将左值转换为右值(允许移动),请使用只有 std :: move
,这是进行这种转换的惯用方法。 std :: forward
不打算以这种方式使用。
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::forward
is not intended to be used this way.
这篇关于std :: forward vs std :: move将lvalue绑定到右值引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!