简体   繁体   中英

Qt object ownership when using lambda as slot

I recently joined a new project, which is full with idiom like: ,

void foo()
{
    Widget* temp = new Widget; 
    connect(temp, &Widget::signalTriggerred,[this, temp ]()
    {
         do cool staff...
    }
}

As you can see no delete nothing, I am afraid even user class "Widget" is inherited QObject, this is still a leak. Does QT do something fancy to prevent leek in case above?

What I am planning to do:

void foo 
{
     std::shared_ptr<Widget > temp( new Widget () );
     connect(temp.get(), &Widget::signalTriggerred,[this, temp] ()
     {
          do even cooler things...
     }
}

Is there a problem with my apporach? (For example I didn't want to use .get() but compiler errors forced me to use it).

Edit : Since there is no parent in my case it is different. Duplicated question seek answer for parent-child cases. I am already aware in that case there will be no leek. In my question I am asking about creating a local QObject based object. And connecting it.

Not quite sure what you're wanting from the question, but if you need to delete the widget and it is derived from QObject, you can delete it in the lambda expression, assuming it's not going to be used after this scope:

void foo()
{
    Widget* temp = new Widget; 
    connect(temp, &Widget::signalTriggerred,[this, temp ]()
    {
         temp->deleteLater();
    }
}

This very much depends on the context.

If the temp widget is actually a visible top-level widget (no parent QWidget ), then the widget needs to be kept alive until the user closes it. You can achieve it getting deleted automatically when being closed using:

widget->setAttribute(Qt::WA_DeleteOnClose);

If the temp widget however is inserted into the layout of some parent widget, Qt will automatically insert it into the QObject ownership tree and temp will have the same lifetime as its parent, see QObject::setParent() .

The shared_ptr by itself saves nothing because it does not answer the question of intended lifetime of widget .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM