[Qt-interest] QList, copy problems

Andre Somers andre at familiesomers.nl
Mon Oct 17 08:23:23 CEST 2011


Op 16-10-2011 15:44, Thiago Macieira schreef:
> On Sunday, 16 de October de 2011 10:32:58 Andre Somers wrote:
>> It might be smarter to use some kind of smart pointer as the thing that
>> you store in your list, instead of a raw pointer. In the case of
>> QObject*s, you could store a QPointer<QObject>  instead, and in the
>> general case you would probably either store a shared pointer or a weak
>> pointer. The actual choices you make, depend on where the ownership of
>> the objects in your list resides, of course.
> Using QList<QPointer<QObject>  >  is not a good idea, for two reasons:
>
> 1) QPointer is not movable, so QList cannot optimise reallocations by memcpy
> (or, more simply, do nothing after realloc). Each QObject keeps a list of all
> QPointers pointing to it. Copying a QPointer involves a function call into
> QtCore.
>
> 2) QPointer is, for that reason, considered deprecated in Qt 4. Do not use it.
>
> A better approach would be to use QSharedPointer and QWeakPointer, which are
> movable. However, both of them run into another limitation of QList in Qt 4
> (to be lifted in Qt 5): they are considered "large". These objects are always
> twice the size of a pointer.
>
> The best solution is QVector<QSharedPointer<OQObject>  >  or
> QVector<QWeakPointer<QObject>  >.
I was going to write something about the nice features of QPointer, but 
I see that QWeakPointer has basically the same features as QPointer did: 
you can use it directly to track a QObject. It is unfortunate though 
that it does not behave like a pointer as QPointer did, but I think I 
understand the reasons for that.

Thanks for correcting me.

André




More information about the Qt-interest-old mailing list