c++ - QT 正常结束线程后,还需要delete线程对象以回收资源吗?
PHPz
PHPz 2017-04-17 14:49:04
0
2
602

QT 的线程正常退出后,是否还需要delete对象,以避免内存泄漏?

//从QThread继承出线程ThreadOnce
class ThreadOnce:public QThread
{
    Q_OBJECT
    void run() Q_DECL_OVERRIDE;
};

//重写run方法,里面不是死循环,跑完后就正常退出线程
void ThreadOnce::run()
{
    int i=0;    
    while(i<20)
    {
        std::cout<<i<<std::endl;
        i++;
    }
}

//是否有必要作如下的信号槽连接(this指向ThreadOnce的实例),来delete ThreadOnce的实例。
connect(this,SIGNAL(finished()),this,SLOT(deleteLater()));
PHPz
PHPz

学习是最好的投资!

reply all(2)
小葫芦

My understanding is that QThread only provides a thread management class. When using it, you can still use it in the same way as classes and objects. After you create a thread object, call the start() function and it will be triggered. run() function starts the running of the thread. If, during the running process, we record some data, these data are generally saved in the data member function of the thread. If you, after the thread is finished running, immediately release the memory of the object , then we cannot get the result through the thread object.

  1. When you are not using the thread object, you can release it;

  2. When there is no need for the thread to end, release the thread;

If this thread is used frequently, I will use the main form pointer as the thread's father. When the father is released, according to Qt's memory management, the child's memory will be automatically released.

黄舟

~~delete or not delete depends on how you create the ThreadOnce object
This is basic knowledge, of course the object on the heap must be your own delete

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template