成员函数返回成员变量的右值引用

cha*_*ink 3 c++ move rvalue-reference move-semantics xvalue

#include <vector>
using namespace std;

struct TempData {
    vector<int> data;
    TempData() {
        for(int i = 0; i < 100; i++) data.push_back(i);
    }
    // vector<int> GetData() { // function 1
    //  return move(data);
    // }
    vector<int>&& GetData() { // function 2
        return move(data);
    }
};

int main() {
    vector<int> v;
    {
        TempData td;
        v = td.GetData();
    }
}
Run Code Online (Sandbox Code Playgroud)

function 1和 和有function 2什么区别?

function 1构造一个 temp vectormove(data)然后将 temp 分配vectorv

没有更多细节可以添加...

Sto*_*ica 5

在您的小测试用例中,可能没有区别。额外的临时对象几乎肯定会被忽略。而vin main 将保存成员变量的内容。

但在一般情况下:

版本 1肯定会使成员data处于某种未指定的“空”状态。即使函数返回值被丢弃。

版本 2可能会使成员处于某种未指定的空状态,也可能不会。例如,如果调用该函数并丢弃其返回值,则该成员将保持不变。这就是为什么可以说它std::move本身不会移动任何东西。