In Stroustrups The fourth release of the C ++ programming language on page 76 shows an example of using the move constructor.
The class is defined as follows:
class Vector {
private:
double∗ elem;
int sz;
public:
Vector(int s) :elem{new double[s]}, sz{s}
{ for (int i=0; i!=s; ++i) elem[i]=0;
~Vector() { delete[] elem; }
Vector(const Vector& a);
Vector& operator=(const Vector& a);
Vector(Vector&& a);
Vector& operator=(Vector&& a);
double& operator[](int i);
const double& operator[](int i) const;
int size() const;
};
The move constructor is defined:
Vector::Vector(Vector&& a) :elem{a.elem},
sz{a.sz}
{
a.elem = nullptr;
a.sz = 0;
}
An example run that I think will cause a memory leak:
Vector f()
{
Vector x(1000);
Vector y(1000);
Vector z(1000);
z=x;
y = std::move(x);
return z;
};
It seems that such a move operation will cause a memory leak, because 1000 items were allocated in y
Vector y(1000);
and a simple reassignment of the pointer in the string y = std :: move (x); will leave these initial 1000 ints that y points to are left on their own. I suggest that the move constructor should have an extra line of code to de-select the 'elem' pointer before the move.