[Qt-interest] What is the use of QWeakPointer
Dan Milburn
danmilburn at clara.co.uk
Fri Apr 9 15:01:07 CEST 2010
Matthias Pospiech wrote:
> Dan Milburn schrieb:
>> Thiago Macieira wrote:
>>
>>> Em Sexta-feira 09 Abril 2010, às 12:02:02, Dan Milburn escreveu:
>>>
>>>> QWeakPointer<MyObject> weakPointer = ...
>>>> MyObject *o = weakPointer.data();
>>>> if( o )
>>>> {
>>>> // Do something with o
>>>> }
>>>>
>>>> Obviously this would cause problems in a multi-threaded environment,
>>>> but then I don't think QWeakPointer is suitable for that.
>>>>
>>> The "proper" way is:
>>>
>>> QSharedPointer<MyObject> sp = weakPointer;
>>> if ( sp ) {
>>> // do something with the shared pointer
>>> // and it won't get deleted
>>> }
>>>
>>>
>>
>> However this won't work if the weak pointer was initialized from a
>> QObject, which seemed to be what the OP was trying to do.
>>
>>
> Indeed, and as far as I understood from the docs - a weakpointer can
> only be constructed with a QObject based class.
> Thus I am little confused.
Things are a little confusing. You're probably thinking of QPointer,
which only accepts QObjects, rather than QWeakPointer, which is
primarily designed to work in conjunction with QSharedPointer, but also
has the QObject tracking functionality.
I would recommend reading Thiago's blog on the Qt smart pointer classes
at
http://labs.trolltech.com/blogs/2009/08/25/count-with-me-how-many-smart-pointer-classes-does-qt-have/.
Dan
More information about the Qt-interest-old
mailing list