gpt4 book ai didi

c++ - std::forward vs std::move 同时将左值绑定(bind)到右值引用

转载 作者:可可西里 更新时间:2023-11-01 18:02:27 26 4
gpt4 key购买 nike

这里move和forward有区别吗:

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)static_cast<typename std::remove_reference<T>::type&&>(t) , 其中Tt 的类型(参见§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是左值,第一个版本被选中。根据标准草案,唯一的效果是forwardstatic_cast<T&&>(t) .与 T正在int ,我们得到 static_cast<int&&>(nb) ,即 - 我们得到两个完全相同的类型转换。

现在,如果您想将左值转换为右值(以允许移动),请仅使用 std::move ,这是进行这种转换的惯用方法。 std::forward不打算以这种方式使用。

关于c++ - std::forward vs std::move 同时将左值绑定(bind)到右值引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6864880/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com