The bane of Dangling Pointers

Ian Monroe ian.monroe at gmail.com
Mon Dec 21 22:22:43 CET 2009


On Mon, Dec 21, 2009 at 2:53 PM, Mark Kretschmann <kretschmann at kde.org> wrote:
> On Mon, Dec 21, 2009 at 1:53 PM, Ian Monroe <ian.monroe at gmail.com> wrote:
>> QSharedPointers can be fairly dangerous if not used correctly. Whereas
>> QPointer is to solve the dangling pointer issue, and are pretty much
>> "free" for any QObject (they just connect to existing signals),
>> QSharedPointers is for memory management. So you have to be mindful
>> when using QShared*Pointers/KSharedPtr (basically you must ensure that
>> the ref-counting is happening correctly by not passing around the bare
>> pointer too much). And I would say its totally overkill if you're only
>> worried about dangling pointers.
>>
>> Also QSharedPointers do their referencing counting inside the pointer
>> object. This is inferior to QSharedDataPointer and KSharedPtr which
>> hold the reference counter inside the object itself (so you can pass
>> the bare pointer, make a QSharedDataPointer or KSharedPtr from it and
>> the counting works just fine). So I'd say to always use KSharedPtr,
>> unless you are holding a pointer to an object defined in a library
>> that you can't derive from QSharedData.
>
> That's right, and I talked to Thiago about this too. Basically, what
> we really want in most cases is Qt 4.6's "QWeakPointer". It's a simple
> Smart  Pointer that is not reference-counting, but yet thread-safe. So
> it's basically a QPointer on steroids.
>
> However, the QWeakPointer implementation is somewhat different in Qt
> 4.5 from that in Qt 4.6. In 4.5 it's not really of much use, and as we
> depend on that still, we can't use the nicer version from Qt 4.6.

Well that's great to hear. 99% of the code in Amarok doesn't do
anything performance related really (all the slow stuff happens in
libraries) so there's really no reason not to use these classes, since
the extra safety they provide is worth it.

Ian


More information about the Amarok-devel mailing list