Vector :: delete with pointer

I manipulate the vectors of objects defined as follows:

class Hyp{ public: int x; int y; double wFactor; double hFactor; char shapeNum; double* visibleShape; int xmin, xmax, ymin, ymax; Hyp(int xx, int yy, double ww, double hh, char s): x(xx), y(yy), wFactor(ww), hFactor(hh), shapeNum(s) {visibleShape=0;shapeNum=-1;}; //Copy constructor necessary for support of vector::push_back() with visibleShape Hyp(const Hyp &other) { x = other.x; y = other.y; wFactor = other.wFactor; hFactor = other.hFactor; shapeNum = other.shapeNum; xmin = other.xmin; xmax = other.xmax; ymin = other.ymin; ymax = other.ymax; int visShapeSize = (xmax-xmin+1)*(ymax-ymin+1); visibleShape = new double[visShapeSize]; for (int ind=0; ind<visShapeSize; ind++) { visibleShape[ind] = other.visibleShape[ind]; } }; ~Hyp(){delete[] visibleShape;}; }; 

When I create a Hyp object, allocate / write memory to visibleShape and add the object to the vector with the vector :: push_back, everything works as expected: the data pointed to by visibleShape is copied using the copy constructor.

But when I use vector :: erase to remove Hyp from the vector, the other elements move correctly. EXCLUDE visibleShape pointer elements that now point to invalid addresses! How to avoid this problem? Did I miss something?

+4
c ++ pointers vector stl erase
Apr 20 2018-10-18T00:
source share
2 answers

I think you are missing an overloaded assignment operator for Hyp .

+2
Apr 20 '10 at 18:56
source share

I think you might miss the assignment operator = in the Hyp class.

Hyp& operator = (const Hyp& rhs);

+1
Apr 20 2018-10-18T00:
source share



All Articles