Search code examples
c++qtqt4

how can Qt delete QObjects?


As I understand, the following code is a perfectly fine way to create a QObject

QLabel *label = new QLabel("label");
QWidget window;
label->setParent(&window);
window.show();

As I am reading everywhere "the parent takes ownership of the newly created object - and eventually calls delete", or "the composite object takes ownership of the children so, as long as the parenting has been done, you can be assured that the child QObjects will be destroyed when the parent is destroyed" (from How does Qt delete objects ? And what is the best way to store QObjects?)

Can someone tell me how can Qt "take ownership" of a QObject? More technically: how is it possible for Qt (which is a library and has its own runtime) to call operator delete on a pointer I created with an operator new from a different runtime? Why doesn't it crash?

EDIT

I am adding this reference as the whole point of the question comes from this:

"The code running in the DLL might be using a different C++ runtime library, which means that the layout of the heap will be different. The DLL might be using a different heap altogether.

Calling delete (in the main program) on a pointer allocated by the DLL (or vice versa) will lead to (at best) an immediate crash or (at worst) memory corruption that'll take a while to track down." (from C++ mix new/delete between libs?)


Solution

  • Let the source code speak instead of mere answers. Here is what QObject's internals do:

    for (int i = 0; i < children.count(); ++i) {
        currentChildBeingDeleted = children.at(i);
        children[i] = 0;
        delete currentChildBeingDeleted;
    }
    children.clear();
    

    Function with the code above is called in destructor. So, it is pretty simple. Parent stores pointers to all of its children. When parent's destructor is being called, it deletes all it's children. This is recursive, as calling delete on object calls its destructor

    Why Qt can safely delete without concerns about runtime library

    Actually, due to name mangling, exporting C++ interface nearly forces You to use the same version of compiler and runtime library. This in very crude way allows Qt to assume that delete is safe to call.