【发布时间】:2011-02-10 06:57:15
【问题描述】:
我正在处理定义如下的对象向量:
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 之外,其他元素都被正确移动了!如何避免这个问题?我错过了什么吗?
【问题讨论】:
-
有什么原因不能将
visibleShape重新定义为:std::vector<double> visibleShape,并完全删除您的复制ctor? -
您似乎没有在默认构造函数中初始化
xmin、xmax等或分配visibleShape,但您在xmin、xmax, etc. to determine that you can read from the other object'svisibleShape 上使用了计算复制构造函数。 -
另外,你所有的数据成员都是公开的,所以你无法控制它是否对你的析构函数中的
delete[] visibleShape有效;它可以分配给任何东西。您应该考虑使用vector或至少将其设为私有,以便您有机会强制执行您的类不变量。 -
@Jerry Coffin:我正在使用 visibleShape 来存储由 Hyp 的其他成员确定大小的图像部分。使用简单指针而不是向量不是更有效吗?我是 C++ 新手,所以我愿意接受建议!
-
@matt:如果效率上存在差异,它会很小 -
vector只是自动执行您需要手动执行的操作...记住您可以使用vector带大小参数的构造函数,或者resize方法,如果你事先知道大小(或者reserve,如果你想使用push_back)。
标签: c++ stl vector pointers erase