主要干了这么件事情:
让ThreadObj继承QThread,重写了run(),在run()里调用了deleteLater()
在main()里
实例化了TheadObj,同时把ThreadObj的finished()信号连接至另一个槽,这个槽会调用ThreadObj的成员
听起来有点繁琐^-^
结果
显示,ThreadObj的析构函数先被调用,然后那个槽才会被调用,而且槽里调用ThreadObj成员也是正确的。
这里不是有点矛盾吗?ThreadObj都被析构了,随后对其成员的调用怎么会正确呢?
代码:
main.h
- #ifndef MAIN_H
- #define MAIN_H
- #include <QtCore/QObject>
- #include <QtCore/QThread>
- #include <QtCore/QDebug>
- #include <QEventLoop>
- #include <QTimer>
- class ThreadObj:public QThread
- {
- Q_OBJECT
- public:
- ThreadObj(QObject *parent=0):QThread(parent) {}
- public slots:
- void print(){ qDebug() <<"In ThreadObj::print(), current thread id is : " << currentThreadId(); }
- protected:
- void run(){
- qDebug() << "Thread is running, current thread id is : " << currentThreadId();
- QEventLoop loop;
- QTimer::singleShot(2000, &loop, SLOT(quit()));
- loop.exec();
- deleteLater();
- qDebug() << "Thread is finished";
- }
- public:
- ~ThreadObj() {
- qDebug() << "delete QThread obj, current thread id is " << currentThreadId();
- }
- };
- class Dummy:public QObject
- {
- Q_OBJECT
- public:
- Dummy(QObject* parent=0):QObject(parent) {}
- public slots:
- void slot() {
- qDebug()<< "In dummy, current threaed id is : " << QThread::currentThreadId();
- b->print();
- }
- public:
- void set(ThreadObj *obj){ b = obj; }
- private:
- ThreadObj * b;
- };
- #endif // MAIN_H
main.cpp:
- #include <QtCore/QCoreApplication>
- #include "main.h"
- #include <QDebug>
- int main(int argc, char *argv[])
- {
- QCoreApplication a(argc, argv);
- qDebug()<<"main thread:"<<QThread::currentThreadId();
- Dummy *dummy = new Dummy;
- ThreadObj * obj = new ThreadObj;
- dummy->set(obj);
- QObject::connect(obj, SIGNAL(finished()), dummy, SLOT(slot()));
- obj->start();
- return a.exec();
- }
这是运行结果:
- main thread: 0x9b0
- Thread is running, current thread id is : 0x1158
- Thread is finished
- delete QThread obj, current thread id is 0x9b0
- In dummy, current threaed id is : 0x9b0
- In ThreadObj::print(), current thread id is : 0x9b0
第4行已经提示myObj的析构函数运行,所以第4行之后myObj应该被销毁
但是第6行又成功地调用了它的print()函数
打印了提示信息,这是为何?