这里的移动和前进有区别吗:
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)
, where T
是类型t
(参见第 20.2.3/6 节)。在你的情况下,它解决了static_cast<int&&>(nb)
.
forward
有点棘手,因为它是为在模板中使用而定制的(以允许完美转发),而不是作为将左值转换为右值引用的工具。
标准库提供了两种重载(一种用于左值引用,第二种用于右值引用,请参阅§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
,我们得到:
int&& forward(int& t) noexcept;
int&& forward(int&& t) noexcept;
自从nb
是左值,选择第一个版本。根据标准草案,唯一的效果是forward
is static_cast<T&&>(t)
. With T
being int
,我们得到static_cast<int&&>(nb)
,即 - 我们得到两个完全相同的演员表。
现在,如果您想将左值转换为右值(以允许移动),请仅使用std::move
,这是进行此转换的惯用方法。std::forward
不打算以这种方式使用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)