Question

I'm experimenting with move semantics and I am wondering what happens if a rvalue refernece goes out of scope. With following code i get runtime problems if I std::move an lvalue into

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

but not into

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

Does anybody know why?

Also, if you swap the two code-blocks in main() you get a different runtime error 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;
    }
Was it helpful?

Solution

Let's start here:

modify1(move(t_mv1));

For constructing the parameter of modify1, the move constructor of T is used:

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

Note the commented line above. By that time, the two data members of *this object are default initialized, which for pointers means they're left with an indeterminate value. Next, the move assignment operator is called:

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

Now when modify1 returns, the parameter object gets destroyed and the destructor of T calls delete on uninitialized pointers, again invoking undefined behaviour

I haven't looked in the second part (with modify3), but I suspect something similar is going on.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top