Question

is the move constructor for a class that holds a dynamically allocated array supposed to delete it? For instance I have:

template<typename T>
class MyVector
{
public:
MyVector()
{
data = new T[32];
capacity = 32;
size = 0;
}

MyVector(const MyVector<T>& o) //The basic copy constructor
{
capacity = o.capacity;
size = o.size;
data = new T[capacity];

for(int i = 0; i < _size; i++)
{
data[i] = o.data[i];
}
}

MyVector(const MyVector<T>&& o) //The move constructor
{
//What goes here?
}

private:
T* data;
unsigned int size;
unsigned int capacity;
};

I understand the move constructor is called when I do something like:

MyVector A; A = MyVector(); //The one on the right gets a move constructor called? So is it supposed to be identical to the copy constructor?

Was it helpful?

Solution

is the move constructor for a class that holds a dynamically allocated array supposed to delete it? For instance I have:

There is nothing to delete. The object is being constructed after all. All it should do is take the resources from the object on the RHS. It should leave the RHS in a reasonable state. For example,

MyVector(MyVector<T>&& o)
{
    data = o.data;
    o.data = nullptr;

    capacity = o.capacity;
    o.capacity = 0;

    size = o.size;
    o.size = 0;
}

Note that, in order for a move constructor to work, the parameter cannot be const. A move constructor modifies its argument.

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