QTimer singleShot or delete
Solved
General and Desktop
-
Is there a difference between calling a singleShot timer and a regular timer with delete after? Is one way better than the other?
For example:void MainWindow::on_pushButton_clicked() { timer = new QTimer(); timer->start(5000); connect(timer,SIGNAL(timeout()),this,SLOT(timerDone())); } void MainWindow::timerDone() { delete timer; qDebug()<<"timer done"; }
void MainWindow::on_pushButton_clicked() { QTimer *timer = new QTimer(); timer->start(5000); timer->setSingleShot(true); connect(timer,SIGNAL(timeout()),this,SLOT(timerDone())); } void MainWindow::timerDone() { qDebug()<<"timer done"; }
-
Hi,
In the second case you wrote you have a memory leak. Setting single shot to true means that the timer will timeout only once after a call to start. not that it will be deleted after that.
-
The first one has a bug. If main window is destroyed before the timer times out you have a memory leak.
The second one also has a bug. You never delete the timer so you have a memory leak.
If you just want a single shot just use the static method and don't bother with manual resource management:
void MainWindow::on_pushButton_clicked() { QTimer::singleShot(5000, this, SLOT(timerDone())); } void MainWindow::timerDone() { qDebug()<<"timer done"; }