- Game Programming using Qt 5 Beginner's Guide
- Pavel Strakhov Witold Wysota Lorenz Haas
- 283字
- 2021-08-27 18:30:57
Automatic deletion of objects
You might have noted that although we created a number of objects in the constructor using the new operator, we didn't destroy those objects anywhere (for example, in the destructor). This is because of the way the memory is managed by Qt. Qt doesn't do any garbage collecting (as C# or Java does), but it has this nice feature related to QObject parent–child hierarchies. The rule is that whenever a QObject instance is destroyed, it also deletes all of its children. This is another reason to set parents to the objects that we create—if we do this, we don't have to care about explicitly freeing any memory.
Since all layouts and widgets inside our top-level widget (an instance of MainWindow class) are its direct or indirect children, they will all be deleted when the main window is destroyed. The MainWindow object is created in the main() function without the new keyword, so it will be deleted at the end of the application after a.exec() returns.
When working with widgets, it's pretty easy to verify that every object has a proper parent. You can assume that anything that is displayed inside the window is a direct or indirect child of that window. However, the parent–child relationship becomes less apparent when working with invisible objects, so you should always check that each object has a proper parent and therefore will be deleted at some point. For example, in our TicTacToeWidget class, the gridLayout object receives its parent through a constructor argument (this). The button objects are initially created without a parent, but the addWidget() function assigns a parent widget to them.