Wednesday, 11 May 2016

Is there a memory leak in this C++ move constructor?

In Stroustrups The C++ Programming Language Fourth Edition, on page 76, there is example of move constructor use.



The class is defined like this:




class Vector { 
private:
double∗ elem; // elem points to an array of sz doubles
int sz;
public:
Vector(int s) :elem{new double[s]}, sz{s}
{ for (int i=0; i!=s; ++i) elem[i]=0; // initialize elements }

~Vector() { delete[] elem; } // destructor: release resources

Vector(const Vector& a); // copy constructor
Vector& operator=(const Vector& a); // copy assignment
Vector(Vector&& a); // move constructor
Vector& operator=(Vector&& a); // move assignment

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}, // "grab the elements" from a 
sz{a.sz}
{
a.elem = nullptr; // now a has no elements
a.sz = 0;
}



Example execution which, I think, will cause memory leak:



Vector f() 
{
Vector x(1000);
Vector y(1000);
Vector z(1000);
// ...
z=x; //we get a copy

y = std::move(x); // we get a move
// ...
return z; //we get a move
};


It seems that such move operation will cause memory leak, because y had been allocated 1000 elements in



Vector y(1000); 



and simple pointer re-assignment at line y = std::move(x); would leave these initial 1000 ints pointed by y left on its own. I assume, the move constructor has to have extra line of code to de-allocate pointer 'elem' before moving.

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...