Do I need to delete QObjects?
Unsolved
General and Desktop
-
Do I need to delete explicitly QObjects like in below code or Qt take care of that memory mangement by itself?
void myClass:startTimer() { auto timer = new QTimer(this); timer->setInterval(1000*5); timer->setSingleShot(true); bool ok = connect(timer, &QTtimer::timeout, [=]() { loop->quit(); }); assert(ok); timer->start(); // do something loop->quit(); }
-
Hi
When you assign a parent, you should not delete it manually. Parent will
new QTimer(this); << this is owner.
http://doc.qt.io/qt-5/objecttrees.html -
Hi,
The
timer
object will get automatically delete when its parent also is but the way you do it, you'll be filling up memory with QTimer objects each time you call your startTimer function. So either delete it explicitly at the end of the method or use a stack variable. -
For this particular example, you don't need to create a
QTimer
object at all, so there is nothing to delete. Just use the static function,QTimer::singleShot()
.Your 6 lines of code can be reduced to 1 line:
QTimer::singleShot( 1000*5, [=]{ loop->quit(); } );