What is the lifespan of the allocated stack in lambda function variables used as slots in Qt

I need help to understand how lambda functions work, to prevent memory leaks when using them. In particular, I would like to know when it foowill be destroyed in the following case:

void MainWindow::onButtonClicked()
{
    QTimer *t(new QTimer(this));
    bool foo = false;

    t->setSingleShot(true);
    t->setInterval(1000);
    t->start();

    connect(t, &QTimer::timeout, [=](){
        delete t;
        qDebug() << foo;
    });
}

What about when used [&]?

+3
source share
2 answers

-. - operator(). -. . , , , . , , - , , , .

. , , , :

  • QObject::disconnect() QObject::connect()

  • QObject .

, - . :

void test1() {
  int a = 5;
  QObject b;
  QObject:connect(&b, &QObject::destroyed, [&a]{ qDebug() << a; });
  // a outlives the connection - per C++ semantics `b` is destroyed before `a` 
}

:

int main(int argc, char **argv) {
  QObject * focusObject = {};
  QApplication app(argc, argv);
  QObject * connect(&app, &QGuiApplication::focusObjectChanged,
                    [&](QObject * obj){ focusObject = obj; });
  //...
  return app.exec();  // focusObject outlives the connection too
}

. :

void MainWindow::onButtonClicked() {
  bool foo = {};
  QTimer::singleShot(1000, this, [this, foo]{ qDebug() << foo; });
}

- (this) singleShot. , this . , this.

, , undefined , . :

void MainWindow::onButtonClicked()
{
  auto t = new QTimer(this);
  bool foo = {};

  t->setSingleShot(true);
  t->setInterval(1000);
  t->start();

  connect(t, &QTimer::timeout, [=](){
    qDebug() << foo;
    t->deleteLater();
  });
}

t foo -. - :

class $OpaqueType {
  QTimer * const t;
  bool const foo;
public:
  $OpaqueType(QTimer * t, bool foo) :
    t(t), foo(foo) {}
  void operator()() {
    qDebug() << foo;
    t->deleteLater();
  }
};

void MainWindow::onButtonClicked() {
  //...
  connect(t, &QTimer::timeout, $OpaqueType(t, foo));
}

lambda - , , , , :

auto f = [&]{ /* code */ };
connect(o, &Class::signal1, this, f);
connect(p, &Class::signal2, this, f);

- , , . - . decltype. decltype , . C++ , , . .

+2

, , , . , operator(), .

, . , , , - , .

, . (, ), , . , , , , . undefined.

+1

All Articles