我在GUI中有一个窗口系统,我不确定销毁顺序。每个窗口都有一个矢量持有其子女,各自也都有一个指向它的父:删除父/子窗口层次结构的最佳方法
auto root = new Window;
root->addChild(new Window);
root->addChild(new Window);
auto child = root->addChild(new Window); // Return value is the newly created Window
child->addChild(new Window);
child->addChild(new Window);
auto grandchild = child->addChild(new Window);
grandchild->addChild(new Window);
grandchild->addChild(new Window);
grandchild->addChild(new Window);
//我要删除的子指针,首先我需要从其父的孩子矢量抹去它的指针。
child->parent->children.erase(child->parent->children.begin() + child->positionInParentsVector - 1);
child->destroy();
void Window::destroy()
{
if (children.size() == 0) delete this;
else for (auto i : children) i->destroy();
}
或与智能指针的载体,那会是足够做:
// Remove reference of child from parent's children vector, then
delete child;
我已阅读,它是确定确实删除了这一点。这很难让我的头脑。
智能指针很可能是最好的所以它是所有自动清理。 但是,如果您的层次结构非常深,您可能会在析构函数中发生堆栈溢出。在这种情况下,您将需要像发布一样“手动”释放所有内容。 –
另外,由于destroy函数是递归的,我只需要在最高级别删除父项的引用,这意味着我需要创建一个函数来删除引用,另一个函数执行递归删除,对吧?这可能是三个函数,一个removeReferenceAndDestroy,并在那个removeReference中,然后执行递归destroy()。没有更优雅的方式? – Zebrafish
如果堆栈溢出*是一个现实的问题(它也会发生在常规层次递归遍历中),那么它实际上*不是*就像你显示的那样,你需要不经过递归而是使用循环。 –