[Qt-interest] QList, copy problems

Thiago Macieira thiago at kde.org
Sun Oct 16 15:44:04 CEST 2011


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> >.

-- 
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
   Software Architect - Intel Open Source Technology Center
      PGP/GPG: 0x6EF45358; fingerprint:
      E067 918B B660 DBD1 105C  966C 33F5 F005 6EF4 5358
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 190 bytes
Desc: This is a digitally signed message part.
Url : http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20111016/89822063/attachment.bin 


More information about the Qt-interest-old mailing list