Should Qt objects be created on the heap or on the stack?1)
If the object is going to be part of a tree of Qt objects (as will be the case for most Qt GUI objects), then it should be created on the heap.
If the object is not part of a tree or is the root of a tree, then it can be created either on the heap or the stack. It seems to be a tradition (or maybe there's a good technical reason for this) to create the main QApplication
object on the stack. It is also typical to create main windows (tree roots) on the stack so that they do not need to be manually deleted.
In contrast to many modern programming languages, C++ has no automatic memory management. The traditional approach to managing dynamically allocated storage in C++ is to explicitly delete allocated memory that you no longer require. When you are dealing with large trees of objects, this can become quite tedious and the source of errors (especially memory leaks).
Qt tries to make up for this by providing automatic memory management for the objects under its domain. Qt user interfaces are almost always made up of a tree of Qt widgets, which are themselves subclasses of Qt objects (i.e., QWidget
s derive from QObject
). Qt automates the destruction of such trees: deleting the root of a tree of Qt objects will automatically delete all children of the root as well. So, managing the destruction of a large Qt interface requires only destroying the root object.
For this to work, there are two requirements:
new
operator.Example:
QObjectSubclass theParent; // create theParent on the stack AnotherQObjectSubclass *foo; // pointer to a child foo = new AnotherQObjectSubclass( "bar", &theParent ); // create foo on the heap and reparent to theParent
When widgets are added to layout managers, they are automatically reparented to the overlying object (typically the layout manager's parent). Therefore, parents are not specified when creating widgets that are added to layout managers. However, you must reparent the layout manager itself.
QWidget mainWindow; // mainWindow is on the stack QVBoxLayout* theLayout = new QVBoxLayout(&mainWindow); // theLayout is on the heap and reparented QLabel* aLabel = new QLabel("One"); // aLabel is on the heap (no parent specified) theLayout->addWidget(aLabel); // aLabel just needs to be added to the layout manager
What happens when layout managers are nested? Do the child managers get automatically reparented? To whom?