移动和前进之间有区别吗:
void test(int && val)
{
val=4;
}
void main()
{
int nb;
test(std::forward<int>(nb));
test(std::move(nb));
std::cin.ignore();
}
Run Code Online (Sandbox Code Playgroud)
Vit*_*tus 29
在您的具体情况下,不,没有任何区别.
详细解答:
引擎盖下,std::move(t)确实static_cast<typename std::remove_reference<T>::type&&>(t),这里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;
Run Code Online (Sandbox Code Playgroud)
替代int,我们得到:
int&& forward(int& t) noexcept;
int&& forward(int&& t) noexcept;
Run Code Online (Sandbox Code Playgroud)
由于nb是左值,因此选择了第一个版本.根据标准草案,唯一的效果forward是static_cast<T&&>(t).随着T存在int,我们得到static_cast<int&&>(nb),即 - 我们得到两个完全相同的演员阵容.
现在,如果你想将左值转换为右值(允许移动),请仅使用std::move,这是执行此转换的惯用方法.std::forward不打算以这种方式使用.
| 归档时间: |
|
| 查看次数: |
2757 次 |
| 最近记录: |