PDA

View Full Version : QThread vs QThread* and QThread: Destroyed while thread is still running warning



Axtroz
4th October 2012, 13:49
Greetings.
I am trying to understand the concept behind using threads and have subclassed QThread the following way:



// Header:

#include <QtDebug>

class TestThread : public QThread
{
public:
void run();
};

// C++ source:

void TestThread::run() {
qDebug() << "Message from thread";
exec();
}

// main.cpp:

#include "testthread.h"

int main(int argc, char** argv) {
TestThread t1, t2;
t1.start();
t2.start();
qDebug() << "Message from main function";
return 0;
}

It returns 2 warnings QThread: Destroyed while thread is still running warning
and then it crashes.
However, if I replace


TestThread t1,t2;

with


TestThread *t1 = new TestThread, *t2 = new TestThread;

it works. My question is: why?

Santosh Reddy
4th October 2012, 14:49
This nothing specific about QThreads, but normal C/C++ behaviour.

Case 1: In which you get warning, TestThread obejcts are created on stack, with local scope, compiler calls destructor at the end of main()
Case 2: In which no warning, TestThread obejcts are created on heap (dynamic object), compiler does not explicitly destroy this, you have write code to manually delete these objects on heap. Objects not destroyed - so no warnning.