我正在尝试将具有指针成员的对象存储在 std::vector 中。据我了解,当调用 push_back 时,会制作传递对象的临时副本并将其发送到向量内部存储器,然后将其销毁。因此,我编写了如下所示的复制构造函数:
class MeltPoint
{
public:
MeltPoint();
MeltPoint(b2Vec2* point);
MeltPoint(b2Vec2* point, Segment* segment, bool intersection);
MeltPoint(MeltPoint const& copy);
MeltPoint& operator= (const MeltPoint& m);
~MeltPoint();
private:
b2Vec2* point;
Segment* segment;
bool intersection;
};
MeltPoint::MeltPoint()
{
CCLog("MeltPoint DEFAULT CONSTRUCTOR");
}
MeltPoint::MeltPoint(b2Vec2* point)
{
CCLog("MeltPoint CONSTRUCTOR");
this->point = new b2Vec2();
*(this->point) = *point;
this->segment = new Segment();
this->intersection = false;
}
MeltPoint::MeltPoint(b2Vec2* point, Segment* segment, bool intersection)
{
this->point = point;
this->segment = segment;
this->intersection = intersection;
}
MeltPoint::MeltPoint(MeltPoint const& copy)
{
CCLog("MeltPoint COPY");
point = new b2Vec2();
*point = *copy.point;
segment = new Segment();
*segment= *copy.segment;
}
MeltPoint& MeltPoint::operator= (const MeltPoint& m)
{
CCLog("MeltPoint ASSIGNMENT");
*point = *m.point;
*segment = *m.segment;
return *this;
}
MeltPoint::~MeltPoint()
{
CCLog("MeltPoint DESTRUCTOR");
delete this->point;
delete this->segment;
}
b2Vec2(Box2D 框架)是一个简单地保存 2D 坐标的结构
Segment 是一个自定义类:
class Segment
{
public:
Segment();
Segment(b2Vec2* firstPoint, b2Vec2* secondPoint);
~Segment();
private:
b2Vec2* firstPoint;
b2Vec2* secondPoint;
};
Segment::Segment()
{
CCLog("Segment DEFAULT CONSTRUCTOR");
this->firstPoint = new b2Vec2(0, 0);
this->secondPoint = new b2Vec2(0, 0);
}
Segment::Segment(b2Vec2* firstPoint, b2Vec2* secondPoint)
{
CCLog("Segment CONSTRUCTOR");
this->firstPoint = firstPoint;
this->secondPoint = secondPoint;
}
Segment::~Segment()
{
CCLog("Segment DESTRUCTOR");
delete firstPoint;
delete secondPoint;
}
在某些函数中,我正在填充向量:
void someFunction()
{
vector<MeltPoint> randomVertices;
randomVertices.push_back(MeltPoint(new b2Vec2(190, 170))); //10
randomVertices.push_back(MeltPoint(new b2Vec2(70, 110))); //9
}
最后的输出:
MeltPoint CONSTRUCTOR
Segment DEFAULT CONSTRUCTOR
MeltPoint COPY
Segment DEFAULT CONSTRUCTOR
MeltPoint DESTRUCTOR
Segment DESTRUCTOR
MeltPoint CONSTRUCTOR
Segment DEFAULT CONSTRUCTOR
MeltPoint COPY
Segment DEFAULT CONSTRUCTOR
MeltPoint COPY
Segment DEFAULT CONSTRUCTOR
MeltPoint DESTRUCTOR
Segment DESTRUCTOR
MeltPoint DESTRUCTOR
Segment DESTRUCTOR
test(1074,0xac7d9a28) malloc: *** error for object 0x844fd90: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
test(1074,0xac7d9a28) malloc: *** error for object 0x844fda0: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
在段析构函数中引发了错误,但我在构造函数中为两个指针成员分配了一个新成员。你能帮我吗?