gpt4 book ai didi

c++在通知父级的同时删除树结构中的所有子级

转载 作者:行者123 更新时间:2023-11-27 22:46:49 27 4
gpt4 key购买 nike

考虑到这一点:

class A {    
public:
A()
~A()
void add(A *child);
void remove(A *child);
void set_parent(A *parent);
private:
A *parent;
std::list<A*> children;
};

add、removeset_parent 显然可以访问列表或父属性。

通过以下实现:

A::A() : parent(nullptr){};
A::~A() {
//Keep the hierarchy clean and inform parent that we are gone now
if(this->parent != nullptr) {
this->parent->remove(this);
}
//Also delete all children as they would be lost now ...
for(A *child : children) {
delete child;
}
}
void A::set_parent(A *parent)
{
if(this->parent != nullptr)
this->parent->remove(this);
this->parent = parent;
}

我实际上不想做任何更复杂的事情,但问题是,当删除列表的子级时,他们每个人都会通知他们的父级他们现在不在了,从而操纵我们当前正在迭代的列表。可以做什么?

最佳答案

在删除子项之前“分离”父项怎么样?

A::~A() {
//Keep the hierarchy clean and inform parent that we are gone now
if(this->parent != nullptr) {
this->parent->remove(this);
}
//Also delete all children as they would be lost now ...
for(A *child : children) {
child->set_parent(nullptr); // Detach parent to avoid re-calling remove()
delete child;
}
}

关于c++在通知父级的同时删除树结构中的所有子级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41743873/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com