Search code examples
c++qtqthread

Using a QThread without new


So I have some sample code below.

workerThread = new QThread();
m_worker->moveToThread( workerThread );
connect( workerThread , SIGNAL( started() ), m_worker, SLOT( createObject() ) );
connect( m_worker, SIGNAL( created() ), this, SLOT( objectReceived() ) );
workerThread->start();

It currently uses a QThread by initializing it with new. If this is the only context it is used in, couldn't I just use "QThread workerThread", reference its address for connection, and be done? This would save the program from putting the thread on the heap. I noticed if I don't use new and use the way I listed, I get the following error "QThread: Destroyed while thread is still running". Nothing changed in the code except the changes I listed. If I use new I do not get this error. Is there a significant difference?


Solution

  • Honestly, there aren't many cases where you can put a QThreadon the stack and do something useful with it before the function returns (and the thread destroyed). Maybe if you block the main thread and wait for the extra thread, but that... somehow defeats the purpose of using an extra thread. If you are going to block the main thread to wait the extra thread, you might as well do the work in the main thread.

    The other case where this may apply is if you use the QThread as a class member instead of a QThread * - in this case it will work, but you lose control over the lifespan of the thread, which may not be ideal. If you have a more static usage scenario - you could do that and save yourself the horrible overhead of dynamic memory allocation...

    At any rate, the overhead of allocating a single QThread dynamically is negligible and should be no cause of concern.