简体   繁体   English

将左值绑定到右值引用时,std :: forward vs std :: move

[英]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) ,其中Tt类型(请参见§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. Tint ,我们得到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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM