Important: Please read the Qt Code of Conduct -

Do I need to delete QObjects?

  • 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);
      bool ok = connect(timer,  &QTtimer::timeout, [=]() {  loop->quit(); });
     // do something 

  • Lifetime Qt Champion

    When you assign a parent, you should not delete it manually. Parent will
    new QTimer(this); << this is owner.

  • Lifetime Qt Champion


    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.

  • An alternative is to connect(timer, &QTimer::timeout,timer, &QTimer::deleteLater);

    You don't need to assert the return of connect when you use Qt5 connect syntax, the compiler will "static assert" it for you

  • Moderators

    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(); }  );

Log in to reply