带指针成员的向量::擦除

发布于 2024-08-29 13:21:52 字数 1106 浏览 2 评论 0原文

我正在操作定义如下的对象向量:

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将该对象添加到向量中,一切都按预期工作:使用visibleShape指向的数据复制复制构造函数。

但是,当我使用 vector::erase 从向量中删除 Hyp 时,其他元素都会正确移动,除了指针成员visibleShape 现在指向错误的地址!如何避免这个问题呢?我错过了什么吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

别在捏我脸啦 2024-09-05 13:21:52

我认为您缺少 Hyp 的重载赋值运算符。

I think you're missing an overloaded assignment operator for Hyp.

绾颜 2024-09-05 13:21:52

我认为您可能缺少 Hyp 类中的赋值运算符 =

Hyp&运算符 = (const Hyp&rhs);

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

Hyp& operator = (const Hyp& rhs);

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文