1
TIPS FOR CORRECT MEMORY MANAGEMENT WITH C++ AND QT
2
==================================================
3
4
5
1)
6
Use of "Smart Pointers":
7
A smart pointer in C++ means (in its most simple incarnation) a
8
pointer that automatically sets itself to 0, when the object it points
9
to is being destroyed (deleted).
10
11
Advantages:
12
13
No risk of "dangling pointers". A dangling pointer is a pointer that
14
has been deleted, but still contains the memory address of the object
15
that has been destroyed. What happens if you delete this again is
16
called a "double-free", and almost always leads to a crash. With a
17
smart pointer, you can delete the object safely again, because
18
deleting a 0-pointer is defined as a safe (doing nothing) operation in
19
the C++ standard.
20
21
Example:
22
23
WRONG:
24
25
QWidget* foo = new QWidget();
26
delete foo;
27
delete foo;
28
<BOOOOM>
29
30
RIGHT:
31
32
QPointer<QWidget> foo = new QWidget();
33
delete foo;
34
delete foo;
35
<not nice, but no crash>
36
37
38
2)
39
Always make sure not to dereference a 0-pointer:
40
41
This is _the_ single most common crash cause in Amarok 2 currently.
42
It's easy to prevent, but unfortunately also easy to miss:
43
44
Example:
45
46
WRONG:
47
48
Meta::TrackPtr foo;
49
debug() << foo->prettyUrl();
50
<BOOOOM>
51
52
RIGHT:
53
54
Meta::TrackPtr foo;
55
if( foo )
56
   debug() << foo->prettyUrl();
57
<no output, and no crash>
58
59
60
3)
61
Never, ever, use private d-pointer classes in QObject derived subclasses:
62
63
What can happen is that you do a "delete d;" in your destructor, and
64
then Qt goes ahead and auto-deletes other QObject pointers contained
65
in the private class again, through means of its automatic deleting of
66
QObjects with a parent Object. -> <BOOOOM>
67
68
Read more about this topic in Michael Pyne's interesting blog article:
69
70
http://www.purinchu.net/wp/2009/02/04/another-programming-tidbit/
71
72
73
4)
74
Use Valgrind:
75
76
This is one of the most advanced memory debugging tools available,
77
it's free, and we even have found volunteers that run regular Valgrind
78
checks (both for memory access bugs and memory leaks) on Amarok trunk.
79
Reading the Valgrind logs correctly is a bit of an art in itself, but
80
I'm willing to explain this in another posting, if there is a demand.
81
82
83
Recommended reading on the topic of memory management is this page of
84
the excellent "C++ FAQ Lite":
85
86
http://www.parashift.com/c++-faq-lite/freestore-mgmt.html