I am manipulating vectors of objects defined as follow:
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 a vector with vector::push_back, everything works as expected: the data pointed by visibleShape is copied using the copy-constructor.
But when I use vector::erase to remove a Hyp from the vector, the other elements are moved correctly EXCEPT the pointer members visibleShape that are now pointing to wrong addresses! How to avoid this problem? Am I missing something?
visibleShape
as:std::vector<double> visibleShape
, and delete your copy ctor completely? – Englerxmin
,xmax
, etc. or allocatevisibleShape
in the default constructor but you use calculation onxmin
, xmax, etc. to determine that you can read from the other object's
visibleShape` in the copy constructor. – Roamdelete[] visibleShape
in your destructor; it could have been assigned to anything. You should consider using avector
or at least make it private so that you have a chance to enforce your class invariants. – Roamvector
is just doing automatically the stuff you otherwise need to do manually... remember you can use thevector
constructor that takes a size parameter, or theresize
method, if you know the size in advance (orreserve
if you want to usepush_back
). – Colby