C++ 转发右值引用的适当方法

C++ 转发右值引用的适当方法,c++,c++11,move,forward,C++,C++11,Move,Forward,我有以下代码: #include <iostream> #include <string> using std::cout; using std::endl; void bar(const std::string& str) { cout << "const str - " << str << endl; } void bar(std::string&& str) { cout <&l

我有以下代码:

#include <iostream>
#include <string>

using std::cout;
using std::endl;

void bar(const std::string& str)
{
    cout << "const str - " << str << endl;
}

void bar(std::string&& str)
{
    cout << "str - " << str << endl;
}

void foo(std::string&& str)
{
    bar(str);
}


int main()
{
    foo("Hello World");
}
#包括
#包括
使用std::cout;
使用std::endl;
空栏(常量std::string和str)
{
引用有效的现代C++

从纯技术的角度来看,答案是肯定的:std::forward可以完成所有功能。std::move不是必需的。当然,这两个函数都不是必需的,因为我们可以在任何地方编写强制转换,但我希望我们同意,那将是,嗯,令人恶心的。std::move的吸引力在于方便、减少出错的可能性和更清晰

在此处使用
std::move

void foo(std::string&& str)
{
    bar(str);
}
将返回
str
作为右值引用(这正是您试图实现的),而使用
std::forward
将返回左值引用(您不感兴趣)或右值引用(因此在本例中相当于
std::move
)显然,使用none只会继续调用
const std::string&str
one,因为
str
是该函数中的左值

一句话:他们会做同样的事情,但使用
std::move
是首选,因为

  • 它避免显式指定模板参数
  • 它更地道
  • 它直截了当地说:
    std::forward
    并不打算以那种方式(cfr.)或在那种情况下使用,尽管它肯定会起作用
我可能同意“我将这个右值引用转发给另一个函数”作为一个独立的句子可能有意义,但它有点忽略了问题的关键。你可以重新连接你的大脑,让它像“继续‘移动’这个右值引用到另一个函数”一样思考


也可能相关:

只要确定它是右值引用,就可以移动它

当无法确定转发是右值引用还是左值引用时,应在模板化代码中使用转发。:)

在模板化代码中&&表示通用引用,可以是右值或左值


还要注意的是,std::move是在不进行任何检查的情况下对其进行强制转换的,与forward不同,因此,如果您不确定应该做什么,则forward更安全,而move则更快。

您可以移动它,当您无法确定它是右值引用还是左值引用时,应在模板化代码中使用forward。:)在模板化代码中&&mean universal reference,可以是右值或左值。@Melko如果你把你的评论作为回答,我可以接受:)