qt:heap_versus_stack
Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revisionNext revision | Previous revisionNext revisionBoth sides next revision | ||
qt:heap_versus_stack [2010/12/06 17:32] – mithat | qt:heap_versus_stack [2010/12/08 22:16] – [Long answer] mithat | ||
---|---|---|---|
Line 1: | Line 1: | ||
- | ====== | + | ====== |
- | C++ lacks automatic | + | Should Qt objects be created on the heap or on the stack? |
- | Qt tries to make up for this by providing automatic memory management for the objects under its domain. | + | ===== Short answer ===== |
+ | 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' | ||
+ | |||
+ | ===== Long answer ===== | ||
+ | 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. | ||
For this to work, there are two requirements: | For this to work, there are two requirements: | ||
- | - All child objects must be created on the //heap//. The root itself may be on the //stack//. (If you need a reminder, the heap is the memory store from which dynamically allocated storage is taken; the //stack// is used for standard variable storage as well as for passing values to function calls.) | + | - All child objects must be created on the heap; however, the root itself may be on the stack. In other words, |
- | - Child objects must explicitly be made children of their parents. | + | - Child objects must explicitly be made children of their parents |
Example: | Example: | ||
Line 18: | Line 26: | ||
===== Automatic Management with Layout Managers ===== | ===== Automatic Management with Layout Managers ===== | ||
- | When widgets are added to [[layout managers]], they are automatically reparented. Therefore, parents are not specified when creating widgets. However, | + | When widgets are added to [[layout managers]], they are automatically reparented |
<code cpp-qt> | <code cpp-qt> | ||
Line 27: | Line 35: | ||
</ | </ | ||
+ | FIXME What happens when layout managers are nested? Do the child managers get automatically reparented? To whom? |
qt/heap_versus_stack.txt · Last modified: 2010/12/08 22:59 by mithat