Search code examples
c++qtqobjectself-destruction

Optimal way to self-delete QObjects


I have two classes Node and NodeContainer:

class Node: public QObject
{
    NodeContainer* parent;
}

class NodeContainer : QObject
{
    bool deleteChild(Node*child)
    {
        if(childNodes->remove(child))
        {
            deleteLater(child);
        }
    }

    QList<Node*> childNodes;
}

A node can either have a parent or not. What is the better way to implement the destruction of the Node class:

1) Access the parent and destroy himself from there

destroy()
{
    if(parent !=0)
    {
        parent.deleteChild(this);
    }
    else
    {
        deleteLater(this);
    }
}

2) Emit a signal, and let the parent destroy it later

destroy()
{
    if(parent !=0)
    {
        //Once the parent receives it, the parent will delete the child.
        emit parentYouHaveToDeleteChild(this);
    }
    else
    {
        deleteLater(this);
    }
}

Solution

  • If the parentYouHaveToDeleteChild signal is connected to the deleteChild slot, there is effectively no difference between the two methods you've presented. The program will not return to the event loop before calling the slot.

    Except that the second method adds the overhead of a signal/slot call.