[Qt-interest] Dereferencing QPointers

Thiago Macieira thiago.macieira at trolltech.com
Sat Apr 18 09:00:15 CEST 2009


Ellen Kestrel wrote:
>I don't want to store them in ClassA as a list
>of pointers, because then I would have to write a destructor to avoid
> memory leaks, and there is no need for them to be pointers.  Does
> anyone know what's going wrong, and how I can make this work?

You have to store them as pointers because you can't store them as values.

QObject's copy constructor is private, as the error message you received 
(and pasted in your email) explained. That means you can't create a copy, 
which QList needs you to do.

You can try Anton's suggestion of not deriving from QObject. If you don't 
need signals and slots, that may be the way because it's simpler.

However, there's another solution, which is to use QSharedPointer<ClassB>. 
The QSharedPointer class controls the lifetime of the object, which allows 
you to place it a QList.

However, since it controls the lifetime, you have to make sure nothing 
deletes the object -- only QSharedPointer can delete it. That means you 
must ensure that all objects controlled by a QSharedPointer have no 
parents.

Also note that QSharedPointer<QObject> has no direct operator QObject*(), 
so everywhere where functions expect QObject*, you'll have to add .data().

-- 
Thiago Macieira - thiago.macieira (AT) nokia.com
  Senior Product Manager - Nokia, Qt Software
      Sandakerveien 116, NO-0402 Oslo, Norway
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: This is a digitally signed message part.
Url : http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20090418/d117a333/attachment.bin 


More information about the Qt-interest-old mailing list