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


in stroustrups c++ programming language fourth edition, on page 76, there example of move constructor use.

the class defined this:

class vector {  private:    double∗ elem; // elem points array of sz doubles    int sz;  public:    vector(int s) :elem{new double[s]}, sz{s}    { (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 defined:

vector::vector(vector&& a) :elem{a.elem}, // "grab elements"    sz{a.sz}  {    a.elem = nullptr; // has no elements    a.sz = 0;  }  

example execution which, think, cause memory leak:

vector f()  {    vector x(1000);    vector y(1000);    vector z(1000);    // ...    z=x; //we copy    y = std::move(x); // move    // ...    return z; //we move  };  

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

vector y(1000);  

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

assuming move constructor implemented properly, no. line refering invokes move assignment, not constructor, because z exists.


Comments