Search code examples
c++c++11movemove-semantics

Move constructor and double delete


Initially I thought that move constructor will not call the temporary object destructor but when I try it is calling the destructor. So when we steal the data from move constructor I am getting double delete error.

#include <iostream>
using namespace std;

class A
{
    public:
    A()
    : name("default")
    {
        cout<<"i am default\n";
        data = new char[20];
    }

    A(A&& t)
    : name("move")
    {
        data = t.data;
        cout<<"i am move\n";
    }

    ~A()
    {
        delete data;
        cout<<"I am done:"<<name<<endl;
    }

    char * data;
    string name;
};

A getA()
{
    A obj;
    return obj;
}

int main()
{
    A test(std::move(getA()));
}

Solution

  • That's because you are not actually "stealing", you're just copying, and so you'll delete 2 times the same pointer, as you noticed.

    To actually "steal" the data, set the original data to nullptr, as it no longer belongs to that object.

    A(A&& t)
    : name("move")
    {
        data = t.data;
        t.data = nullptr; //'t' doesn't own its data anymore
        cout<<"i am move\n";
    }
    

    You could also use std::swap (thanks @RemyLebeau):

    A(A&& t) : name("move"), data(nullptr)
    {
        std::swap(data, t.data);
        cout << "i am move\n";
    }