[Qt-interest] What is the use of QWeakPointer

Dan Milburn danmilburn at clara.co.uk
Fri Apr 9 13:45:55 CEST 2010


Matthias Pospiech wrote:
> Dan Milburn schrieb:
>> The way I use it is as follows:
>>
>> QWeakPointer<MyObject> weakPointer = ...
>> MyObject *o = weakPointer.data();
>> if( o )
>> {
>>     // Do something with o
>> }
>>   
> Here you are converting a weak pointer to a normal pointer and use the 
> normal pointer in the following.
> I could implement the same without the weak pointer. So where is the 
> actual benefit?

That was certainly not intended to be a complete example, merely how I 
would use it to get around the lack of -> operator.  Typically the 
QWeakPointer will be held as a member variable of a class, and would be 
used where you want to hold on to a reference in that class but it is 
not the 'owner' of the object being pointed to.

class MyClass
{
private:
   QWeakPointer<MyObject> weakPointer;

public:
   MyClass(){}

   void setMyObject( const QWeakPointer<MyObject> &p )
   {
     weakPointer = p;
   }

   void doSomething()
   {
     MyObject *o = weakPointer.data();
     if( o )
     {
       // Do something with o
     }
     else
     {
       // Do something else
     }
   }
};

The benefit is that if the object gets deleted externally to your class, 
the QWeakPointer will be set to null so you do not have a dangling 
pointer to an object that doesn't exist, as might happen with a normal 
pointer (note also that it doesn't have to be initialized in the 
constructor because the QWeakPointer is set to null automatically).

Dan



More information about the Qt-interest-old mailing list