Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

qt garbage collection and smart pointers

Im thinking of starting using smart pointers in my qt work.The thing that confuses me how smart pointers would go with Qt garbage collection. The whole Qt stands on idiom that child QObject constructs with QObject* parent as ctor argument and therefore enables garbage collection. For example:

     QWidget* mWidget = new QWidget(this);//Here we not only 
                                          //ensure that mWidget will be deleted  
                                          //when its parent is deleted, but also tell qt,  
                                          //that mWidget is not a window, but belongs to 
                                          //parent's layout         

Now if i want to wrap mWidget into the smart pointer.

 typedef QScopedPointer<QWidget> WidgPtr;
 WidgPtr mWidget = WidgPtr(new QWidget(this));

But now when parent's dtor is called it will call delete on mWidget's pointer twice. First due to garbage collection, second when smart pointer dtor is called.

Of course we can construct mWidget without parent and then change some flags to turn off window behaviour or call setParent() (But then again mWidget will be deleted twice). But to me its too much to do such a complex initialization only to be able to use smart pointers instead of raw pointers. Or maybe i miss something? Thanks.

like image 505
Alexander Avatar asked Oct 13 '12 08:10

Alexander


1 Answers

QScopedPointer and QSharedPointer are not aware of whether their target object lives or dies, so if you keep the smart pointer anywhere else than among member variables, then yes, in your case destructor might be called twice. That's why these kinds of smart pointers are badly suited for QObjects (but they can still be useful when your object doesn't have a parent).

If you need to keep a guarded pointer to QObject, use QPointer: it will become null once the object is destroyed, so you can delete it at any moment without fear of causing any mayhem. But remember that QPointer will NOT destroy referenced object in destructor. In most cases you should build hierarchies of QObjects and just let the ownership system clean up the memory.

like image 80
Septagram Avatar answered Oct 11 '22 20:10

Septagram