我有两个类 Node 和 NodeContainer:
class Node: public QObject
{
NodeContainer* parent;
}
class NodeContainer : QObject
{
bool deleteChild(Node*child)
{
if(childNodes->remove(child))
{
deleteLater(child);
}
}
QList<Node*> childNodes;
}
节点可以有父节点,也可以没有父节点。 实现 Node 类销毁的更好方法是什么:
1) 访问父级并从那里销毁自己
destroy()
{
if(parent !=0)
{
parent.deleteChild(this);
}
else
{
deleteLater(this);
}
}
2)发出信号,让父级稍后销毁
destroy()
{
if(parent !=0)
{
//Once the parent receives it, the parent will delete the child.
emit parentYouHaveToDeleteChild(this);
}
else
{
deleteLater(this);
}
}
最佳答案
如果 parentYouHaveToDeleteChild
信号连接到 deleteChild
插槽,则您提供的两种方法实际上没有区别。在调用槽之前,程序不会返回事件循环。
除了第二种方法增加了信号/槽调用的开销。
关于c++ - self 删除 QObjects 的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9522559/