0

我正在试验移动语义,我想知道如果右值引用超出范围会发生什么。使用以下代码,如果我 std::move 一个左值,我会遇到运行时问题

function(T t) with t = std::move(lvalue) --> SEGFAULT OR double free

但不进入

function(T &&t) with t = std::move(lvalue) --> OK

有人知道为什么吗?

此外,如果你在 main() 中交换两个代码块,你会得到一个不同的运行时错误 0_o

// Compile with:
// g++ move_mini.cpp -std=c++11 -o move_mini
#include <iostream>
#include <sstream>
#include <string>
#include <algorithm>
#include <list>
#include <utility>
using namespace std;

int num_copied;

class T{
    public:
    T() : a(nullptr), b(nullptr){};

    T(const T &t) : a(new string(*t.a)), 
                    b(new string(*t.b)){
        num_copied++;
        };

    T(T &&t){
        *this = move(t);
        };

    T(string s1, string s2){
        this->a = new string(s1);
        this->b = new string(s2);
        };

    ~T(){
        delete this->a;
        delete this->b;
        };

    T& operator=(const T &lhs){
        num_copied++;
        delete this->a;
        delete this->b;
        this->a = new string(*lhs.a);
        this->b = new string(*lhs.b);
        return *this;
        };

    T& operator=(T &&lhs){
        swap(this->a, lhs.a);
        swap(this->b, lhs.b);
        return *this;
        };

    string *a;
    string *b;
    };

void modify1(T t){
    }

void modify3(T &&t){
    }

int main(){
    cout << "##### modify1(T t) #####" << endl;
    T t_mv1("e", "asdsa");
    num_copied = 0;
    modify1(move(t_mv1));
    cout << "t = move(t_mv)          copies " << num_copied << " times." << endl;
    cout << endl;

    cout << "##### modify3(T &&t) #####" << endl;
    T t_mv3("e", "aseeferf");
    num_copied = 0;
    modify3(move(t_mv3));
    cout << "t = move(t_mv)          copies " << num_copied << " times." << endl;
    cout << endl;

    return 0;
    }
4

1 回答 1

5

让我们从这里开始:

modify1(move(t_mv1));

为了构造 的参数modify1,使用了 的移动构造函数T

T(T &&t){
    *this = move(t);         // <--- this calls move assignment operator
};

请注意上面的注释行。到那时,*thisobject 的两个数据成员已默认初始化,这对于指针意味着它们留下了一个不确定的值。接下来,调用移动赋值运算符:

T& operator=(T &&lhs){
    swap(this->a, lhs.a); // reads indeterminate values and invokes
    swap(this->b, lhs.b); // undefined behaviour
    return *this;
};

现在,当modify1返回时,参数对象被销毁,T调用delete未初始化指针的析构函数再次调用未定义的行为

我没有看过第二部分(带有modify3),但我怀疑正在发生类似的事情。

于 2013-09-15T20:15:23.407 回答