Jor*_*ell 3 c++ pointers list c++11
我有一个std::list的Entity对象(屏幕上的对象).在一个类中EntityContainer,我有一个指向不同实体的指针列表.当a EntityContainer被破坏时,我希望该列表中的所有实体也被破坏.我怎么能这样做,同时避免导致删除列表成员的迭代器错误?
EntityContainer::~EntityContainer()
{
// Destroy children
int numChildren = children.size();
for (int i = 0; i < numChildren; i++)
{
Entity*& child = children.back();
delete child;
}
}
Run Code Online (Sandbox Code Playgroud)
上面导致std :: list :: clear()中的空指针访问冲突,它在销毁期间被调用EntityContainer,因为它是该对象的成员变量.我相信这是因为我删除了列表中的对象,所以当然删除它们时会尝试访问它们.但是,我的问题是,如果我只是保留它,并允许列表clear()而不显式删除其中的对象,则永远不会调用它们的析构函数.我只能假设这是因为列表只破坏列表中的指针,而不是指针指向的对象.这主要是作为假设 - 我可能是错的.你会怎么做?
Pra*_*ian 12
假设children定义为
std::list<Entity *> children;
Run Code Online (Sandbox Code Playgroud)
你可以delete使用以下元素:
for(auto&& child : children) {
delete child;
}
children.clear(); // not really needed since this code is in the destructor
Run Code Online (Sandbox Code Playgroud)
这里没有问题使得任何迭代器无效,因为你实际上并没有从中删除任何元素list,只是破坏了列表元素所指向的对象.该list会还含有相同数量的元素后for声明中完成,只有他们会在该点处无效的内存被人指指点点.
但实际上,不要使用原始指针容器.定义children为
std::list<std::unique_ptr<Entity>> children;
Run Code Online (Sandbox Code Playgroud)
然后你可以摆脱析构函数的定义.
| 归档时间: |
|
| 查看次数: |
10503 次 |
| 最近记录: |