0

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.

Frank Osterfeld
  • 24,815
  • 5
  • 58
  • 70
Kadir Erdem Demir
  • 3,531
  • 3
  • 28
  • 39
  • I am aware of child-parent relationship if object is a QObject there won't be any leek.In my situation QObject is created locally nobody owns the object. Also no parent destoryed or anything . And binded to a signal. I read suggested the question it does not answers my question. – Kadir Erdem Demir Jun 10 '15 at 06:46

2 Answers2

0

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();
    }
}
TheDarkKnight
  • 27,181
  • 6
  • 55
  • 85
0

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.

Tilman Vogel
  • 9,337
  • 4
  • 33
  • 32