Documentation suggesting implementing QTimer as a pointer, why is that?
-
In the official documentation, we are given this piece of sample code, where a QTimer is declared as a pointer.
QTimer *timer = new QTimer(this); connect(timer, &QTimer::timeout, this, QOverload<>::of(&AnalogClock::update)); timer->start(1000);
Why does QTimer need to be declared as a pointer? Are there any known issues with declaring QTimer as an object, like so?
QTimer timer;
-
@Dummie1138
You can use a stackQTimer timer
instead of a heap one if you wish. But you must then look at what its scope/lifetime is. We spend a lot of time here with people using stack objects which go out of scope when they don't intend them to.... -
@Dummie1138 said in Documentation suggesting implementing QTimer as a pointer, why is that?:
My application of this timer should be under 20 seconds so I'm assuming placing it on the stack for me is not going to be too big of an issue
use heap.
-
@Dummie1138 said in Documentation suggesting implementing QTimer as a pointer, why is that?:
for me is not going to be too big of an issue
Depending on what exactly you are doing (where you are declaring the QTimer actually?) you may be wrong.
What do you think how long does the timer exist in the code bellow:void MyClass::myMethod() { QTimer timer; // Do something }
And how long does it exist bellow:
void MyClass::myMethod() { QTimer *timer = new QTimer(); // Do something }
Do you see the difference?