I have the following code:
void class::Testfunc()
{
QTimer* timer = new QTimer;
QObject::connect(timer, &QTimer::timeout, [this](){
emit Log("Time out...");
TestFunc(serverAddress, requestsFolderPath);
// deleteLater(); //*** why does this crash if used to replace the connect below?
});
connect(timer, &QTimer::timeout, timer, &QTimer::deleteLater);
timer->setSingleShot(true);
timer->start(1000);
}
A single shot timer is created with a timout connected to a lambda function that logs the entrance to the lambda function each second (prints text to stdout) and calls the function again.
This works without issue. However, if I remove the connect call to deleteLater (below the lambda function), but enable the deleteLater call in the lambda function, the function fails. It prints once and shortly after, crashes in trying to delete the timer object.
What is the difference between the two deleteLater calls in this instance and why would placing the deleteLater in the lambda function cause a problem here, whereas creating a separate connection works as expected, even though both are calling deleteLater in response to the Timer's timeout signal?
deleteLater
in the lambda callsmyclass::deleteLater
instead ofQTimer::deleteLater
. So make sure you capture both[this,timer]
and usetimer->deleteLater();
– Ketchan