【发布时间】:2017-09-04 11:30:00
【问题描述】:
我在 C++ 中使用类之间共享的指针释放内存时遇到问题。
一个例子:
我的顶点定义为:
class Vertex{
double x;
double y;
}
正方形定义为:
class Square{
Square(Vertex* a, Vertex* b, Vertex* c, Vertex* d);
~Square(); // destructor
Vertex* a;
Vertex* b;
Vertex* c;
Vertex* d;
}
我的析构函数是这样实现的:
Square::~Square(){
delete a;
delete b;
delete c;
delete d;
}
我的方块存储在std::vector<Square*> squares,所以为了清理我所有的记忆,我会这样做:
for(unsigned int i = 0; i < squares.size(); i++){
delete(squares.at(i));
}
那么问题是什么?如果两个正方形共享一个顶点,我的程序会崩溃,因为它试图删除一个不再存在的指针。 我怎么解决这个问题?
【问题讨论】:
-
不要手动分配内存?
-
使用std::shared_ptr。这样,您就不必自己管理内存。
-
指向顶点的共享指针拼写为
std::shared_ptr<Vertex>。 -
Using std::shared_ptr 如果没有更多对象使用它,它将调用析构函数。或者如果相同的顶点是“共享的”,则使用堆栈上的数据会导致冗余。对于像你这样的小对象:
Vertex这并没有太多的内存开销。 -
@AndreKampling 使用
std::vector代替std::shared_ptr有很多区别?
标签: c++ pointers memory-management shared-ptr