我正在处理定义如下的对象向量:
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;};
};
当我创建一个 Hyp 对象时,为 visibleShape 分配/写入内存并将该对象添加到带有 vector::push_back 的向量中,一切都按预期工作:使用 copy-constructor 复制 visibleShape 指向的数据。
但是,当我使用 vector::erase 从向量中删除一个 Hyp 时,除了现在指向错误地址的指针成员 visibleShape 之外,其他元素都被正确移动了!如何避免这个问题?我错过了什么吗?