Tips on memory management with C++ and Qt
Mark Kretschmann
kretschmann at kde.org
Tue Feb 17 08:47:03 CET 2009
On Tue, Feb 17, 2009 at 8:34 AM, Maximilian Kossick
<maximilian.kossick at googlemail.com> wrote:
>>> > 3)
>>> > Never, ever, use private d-pointer classes in QObject derived subclasses:
>>> >
>>> > What can happen is that you do a "delete d;" in your destructor, and
>>> > then Qt goes ahead and auto-deletes other QObject pointers contained
>>> > in the private class again, through means of its automatic deleting of
>>> > QObjects with a parent Object. -> <BOOOOM>
>>> >
>>> > Read more about this topic in Michael Pyne's interesting blog article:
>>> >
>>> > http://www.purinchu.net/wp/2009/02/04/another-programming-tidbit/
>>>
>>> This is not correct. Using d-pointers in QObjects is perfectly fine as
>>> long as the destructors are written correctly. The referenced article
>>> only says that one has to be careful about deleting a private
>>> d-pointer when other classes keep pointers to members of the private
>>> class around.
>>
>> For Amarok, it's a very good rule. As far as I'm aware, there are no parts of
>> Amarok that have binary compatibility guarantees, and so there are no parts of
>> Amarok that have any use for d-pointers.
>>
>> Since a common cause of memory leaks is people forgetting to delete d-
>> pointers, I would suggest not ever using d-pointers in Amarok. The reason for
>> their existance in kdelibs, for example, is that it helps maintain binary
>> compatibility. If you don't need to maintain binary compatility, don't use d-
>> pointers.
>
> d-pointers are used to keep down compile time after changes to one of
> our core classes. And they aren't diffucult to use, at least if one
> stops to think about object ownership when writing them from time to
> time. And that's really the whole point of the article markey linked
> too. "do not use d-pointers" is the wrong conclusion of that article.
Max, while you are perfectly right that d-pointers _can_ be used
correctly by experienced C++ programmers (e.g. like you), my tutorial
was aimed more at beginner C++ coders. And for them it's surely not
good advice to use such advanced techniques, especially not if the
risk is so high and there is no real need.
As an example demonstrating the risks directly in Amarok, please let
me point you to one of my recent commits, where I fixed exactly the
problem I was describing, in a class that absolutely had no need for a
d-pointer:
http://websvn.kde.org/?view=rev&revision=921999
--
Mark Kretschmann
Amarok Developer
www.kde.org - amarok.kde.org
More information about the Amarok-devel
mailing list