【问题标题】:Why does an assignment from an rvalue reference type not invoke the move assignment operator? [duplicate]为什么右值引用类型的赋值不调用移动赋值运算符? [复制]
【发布时间】:2016-09-08 12:53:53
【问题描述】:

考虑以下代码:

#include <iostream>
#include <string>

struct my_struct {
    void func(std::string&& str) {
        str_ = str;
    }

    std::string str_;
};

int main() {
    my_struct s;
    std::string str("Hello");

    s.func(std::move(str));

    std::cout << str << std::endl;
    std::cout << s.str_ << std::endl;    
}

为什么我在my_struct::func 中需要一个额外的std::move 才能调用std::string 的移动赋值运算符?额外的std::move 究竟会做什么?我认为它只会将给定类型转换为其右值引用对应物?

【问题讨论】:

    标签: c++ c++11 move-semantics


    【解决方案1】:
    void func(std::string&& str) {
        str_ = str;
    }
    

    应该是

    void func(std::string&& str) {
        str_ = std::move(str);
    }
    

    str 有名字,左值也有。

    【讨论】:

      【解决方案2】:

      当您执行str_ = str; 时,str 是一个命名变量。这意味着在您的函数内部 str 是一个左值,而不是一个右值。这意味着使用复制分配而不是移动分配。

      您需要做的是将str 恢复为右值,您可以使用std::move 来做到这一点

      str_ = std::move(str);
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-21
      • 1970-01-01
      • 2020-05-16
      • 2019-02-05
      • 1970-01-01
      • 2014-01-27
      • 2019-04-20
      • 2015-05-23
      相关资源
      最近更新 更多