gpt4 book ai didi

c++ - 使用转发引用时,std::move 是否需要与 std::forward 结合使用?

转载 作者:行者123 更新时间:2023-11-30 03:57:43 25 4
gpt4 key购买 nike

在使用通用引用时,std::move 是否需要与 std::forward 结合使用?例如下面两段代码,哪一段是正确的?

void bar(auto && x) {
auto y(std::move(std::forward<decltype(x)>(x)));
}

void bar(auto && x) {
auto y(std::move(x));
}

基本上,我想将 x 的内存移动到 y 中,我不关心它是左值引用还是右值引用。当然,我不想在此处使用 const 值。

最佳答案

move 如果您想移动regardless 参数的值类别就足够了。
forward 在这种情况下是多余的,因为 move(forward(x)) 始终是右值,无论 forward(x) 是。

如果您只想根据 bar 的参数是否为右值来移动,您应该单独使用 forward,它会传播值类别。

关于c++ - 使用转发引用时,std::move 是否需要与 std::forward 结合使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27810381/

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