Qt garbage collection and smart pointers

It seems to me that I'm starting to use smart pointers in my qt work. The thing that bothers me is how smart pointers will go with Qt's garbage collection. All Qt stands on the idiom that a child QObject builds with QObject * parent as the ctor argument and therefore allows garbage collection. For instance:

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 layout 

Now, if I want to wrap mWidget in a smart pointer.

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

But now, when the parent dtor is called, it will delete twice by the mWidget pointer. First, due to garbage collection, and secondly, when the dtor smart pointer is called.

Of course, we can build mWidget without a parent, and then change some flags to disable window behavior or call setParent () (but then again mWidget will be deleted twice). But for me it is too much to do such a complicated initialization just to be able to use smart pointers instead of raw pointers. Or maybe I missed something? Thanks.

+4
source share
1 answer

QScopedPointer and QSharedPointer do not know if their target lives or dies, so if you save the smart pointer elsewhere, except for member variables, then yes, in your case, the destructor can be called twice. That's why these smart pointers are poorly suited for QObjects (but they can still be useful when your object does not have a parent).

If you need to save a protected pointer to a QObject , use QPointer : it will become null after the destruction of the object, so you can delete it at any time, without fear of causing any chaos. But remember that QPointer will NOT destroy the reference object in the destructor. In most cases, you should create QObjects hierarchies and just let the ownership system clear the memory.

+4
source

Source: https://habr.com/ru/post/1439524/


All Articles