user815129
user815129

Reputation: 2314

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?)

Upvotes: 4

Views: 2887

Answers (2)

bartop
bartop

Reputation: 10315

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.

Upvotes: 4

dimm
dimm

Reputation: 1798

for Qt (which is a library and has its own runtime)

This is where your assumption is wrong. Firstly, there is no such thing as "runtime" for the OS. "Runtime" is an informational term.

Modern operating systems have things like: binary executable, shared libraries aka dynamically linked libraries aka DLL, static libraries, processes, threads, etc.

In this case, your executable and the Qt shared library are loaded into the SAME process, which means the memory is shared among them. That means your executable can see Qt memory and conversely Qt can see your memory.

Upvotes: 1

Related Questions