为什么来自右值引用类型的赋值不会调用移动赋值运算符?

时间:2016-09-08 12:53:53

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

请考虑以下代码:

#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;    
}

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

2 个答案:

答案 0 :(得分:2)

SELECT
   *
FROM
(
   SELECT
      *,
      RANK() OVER (PARTITION BY category ORDER BY price)   AS category_price_rank
   FROM
      your_table
)
   ranked_your_table
WHERE
   category_price_rank = 1

应该是

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

因为void func(std::string&& str) { str_ = std::move(str); } 有一个名字,所以是一个左值。

答案 1 :(得分:1)

执行class Test { @Factory(dataProvider = "dp") public Test(int i) { //... some code } @DataProvider public static Object[][] dp(ITestContext context, Method method) { // need to get currently created class by factory // method is null here // not found any way to obtain this class from test context } } 时,str_ = str;是一个命名变量。这意味着你的函数str内部是左值,而不是右值。这意味着使用了复制分配而不是移动分配。

您需要做的是将str恢复为左值,然后您可以使用str

进行此操作
std::move
相关问题