[Interest] Proper use of SharedPointer/WeakPointer
Jason H
scorp1us at yahoo.com
Thu Feb 23 15:40:29 CET 2012
Hrm, my objects *do* have parents, and when the parent goes, the children need to go too. How is that resolved?
________________________________
From: André Somers <andre at familiesomers.nl>
To: interest at qt-project.org
Sent: Thursday, February 23, 2012 9:37 AM
Subject: Re: [Interest] Proper use of SharedPointer/WeakPointer
Op 23-2-2012 15:29, Thiago Macieira schreef:
> On quinta-feira, 23 de fevereiro de 2012 06.26.19, Jason H wrote:
>> So in a return-everything query function, it would look like:
>>
>> QList<QSharedPointer<QObject*> > ObjectDatabase::returnAll()
>> {
>> QList<QSharedPointer<QObject*> > results;
>> foreach (const obj, m_pObjects)
>> {
>>
>> results<< QSharedPointer(obj);
>> }
>>
>> return results;
>> }
>>
>> Yes?
> No.
>
> It is something like this:
>
> QList<QSharedPointer<QObject*> > ObjectDatabase::returnAll()
> {
> return m_pObjects;
> }
>
> You must already have those objects in QSharedPointer somewhere. Otherwise
> QSharedPointer *will* delete them.
Also, to make the whole thing a bit more readable, I prefer to define
typedefs for all classes that I use as a shared pointer. I postfix SPtr
to the name of the class for the shared pointer version, but that's a
matter of preference. I guess some convention would be good.
Thiago's advice is good though: if you use smart pointers, make sure you
use them everwhere, especially for shared pointers. Any place where you
see something else besides a new inside the constructor of a shared
pointer, you know you have a problem. So:
MyClassSPtr obj = MyClassSPtr(new MyClass); //ok
MyClassSPtr obj2 = MyClassSptr(someRawMyClassPtr); // ALERT! Trouble
about to happen!
Also, beware of QSharedPointer lifetime management interfering with
QObject lifetime management. IMO, shared pointers of QObjects better
*not* have parents:
MyClassSPtr obj3 = MyClassSPtr(new MyClass(parentQObject); //could spell
big trouble!
André
_______________________________________________
Interest mailing list
Interest at qt-project.org
http://lists.qt-project.org/mailman/listinfo/interest
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20120223/69adc6b7/attachment.html>
More information about the Interest
mailing list