c++ - 在通用引用上前进与前进

标签 c++ move forward

我正在通过对通用引用应用 std::movestd::forward 来尝试一个程序。直到今天,我都认为两者是相同的,但在这个程序(如下所示)中,输出让我感到惊讶。

#include <iostream>
#include <string>
#include <utility>
using namespace std;

class X
{
    string take="";
    public:
    template<class T>
    void pass1 (T &&str)   // str is a universal reference as it can bind to anything, both rvalue and lvalue references
    {
        take=move(str);
    }
    template<class T>
    void pass2 (T &&str)
    {
        take=forward<T>(str);
    }
    void show()
    {
        cout<<"take = "<<take<<"\n";
    }
}obj;

int main()
{
    cout<<"using move on universal reference:-\n";
    string str="he is there";
    cout<<"str = "<<str<<'\n';
    obj.pass1(str);
    obj.show();
    if (str.empty())
    cout<<"str is empty\n\n";
    else
    cout<<"str isnt empty\n\n";
    cout<<"using forward on universal reference:-\n";
    str="he was there";
    cout<<"str = "<<str<<'\n';
    obj.pass2(str);
    obj.show();
    if (str.empty())
    cout<<"str is empty\n\n";
    else
    cout<<"str isnt empty\n\n";
    return 0;
}

输出:

using move on universal reference:-
str = he is there
take = he is there
str is empty

using forward on universal reference:-
str = he was there
take = he was there
str isnt empty
*/

我的问题是:

  1. 为什么输出不同?
  2. 难道 moveforward 的工作方式相似吗?它们的工作方式有何不同(在上述代码的上下文中)?

最佳答案

T && 已重命名为转发引用。

在您的第一个示例中,您明确调用了 std::move所以 str 成为右值引用,它的内容从 main move 到 X 中的成员。

在第二个示例中,您使用 std::forward .当 T 是右值引用时,在 T 上调用 std::forward 会将右值引用转发给 operator=operator=(std::String&&) 将被调用。如果 T 是左值,则传递左值引用。因为我们有一个左值,所以 operator=(const std::string&) 将被调用,我们复制 str 而不是从它 move 。

关于c++ - 在通用引用上前进与前进,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32952913/

相关文章:

javascript - 如何制作每个页面加载运行一次的 ssl 转发脚本

c++ - 创建和调用函数

c++ - 为什么模板只能在头文件中实现?

c++ - 如何正确地从函数返回中 move 对象?

linux - Bash/Shell-将所有文件从子目录 move 到目标目录?

ssl - nginx:将 ssl 连接转发到另一台服务器

tomcat - 本地主机转发本地主机 :8080/blah in tomcat6

c# - 在 C# 中编辑字符串中的字符

c++ - 如何保持循环直到函数返回?

macos - 我试图告诉 Finder 使用 AppleScript move 文件。但我不知道如何处理重复/替换/跳过