2014-02-28 31 views
0
//my_class.h 

    void My_class::My_Class(){ 

    my_ip=... 
    my_port=... 
    }; 

    void Data_Send_Func(){ 

// send data over tcp; 

} 

    void My_Class::~My_Class(){ 

    cout<<"Delete objects"<<endl; 

    } 

    void My_Class::process(){ 

    QTimer my_timer; 
    my_timer->setInterval(30); 
    connect(my_timer,SIGNAL(timeout()),this,SLOT(Data_Send_Func())); 
    connect(this,SIGNAL(destroyed()),mytimer,SLOT(deleteLater)); 
    } 


    //my_application.cpp 
    My_application::My_application:QCoreApplication{ 

    my_class=new My_Class(); 

    QThread thread=new QThread(); 

    my_class->moveToThread(thread); 

    connect(thread,SIGNAL(started()),my_class,SLOT(process())) ; 

    connect(my_class,SIGNAL(finished()),thread,SLOT(quit())) ; 

    connect(thread,SIGNAL(finished()),thread,SLOT(deletelater())) ; 

    connect(my_class,SIGNAL(finished()),my_class,SLOT(deletelater())) ;   

} 

    //my_application.h 

struct Exit_App{ 

    Exit_App(){ 

    signal(SIGINT,&Exit_App::Exit_F); 
    signal(SIGTERM,&Exit_App::Exit_F); 
    signal(SIGBREAK,&Exit_App::Exit_F); 

    } 
    static void Exit_F(int sig){ 

     cout<<"Exiting App"<<endl; 

     QCoreApplication::exit(0); 
    } 
} 


int main(argc,char* argv[]){ 

    Exit_App app; 
    My_application a(arcg,argv); 
    return a.exec(); 

} 

對象和線程實例所以,當我結束我的節目,我想刪除My_Class析構函數的對象。如何刪除QCoreApplication析構函數

我不想在應用程序中發出fnished信號,所以我想刪除my_application析構函數中的my_class對象和線程。

My_application::~My_application{ 
    if (my_class->thread()) { 

    connect(my_class, SIGNAL(destroyed()), thread, SLOT(quit()); 

    my_class->deleteLater(); 

    } else { 

    delete my_class; // It's a threadless object, we can delete it 
    thread->quit(); 
    } 
    thread->wait(); 

} 
+0

究竟什麼不起作用?程序是否崩潰,或者在執行析構函數時是否顯示一些錯誤消息,或者以其他方式行爲不當? – Frank

+0

@Frank我在入口處放了一些調試代碼並退出到析構函數。入口調試字符串被打印,但退出從不是 – barp

+0

@barp您需要顯示完整的自包含測試用例。你的構造函數不會被調用,順便說一句,但那是因爲你定義了錯誤的構造函數! –

回答

2

QObject不能從任何線程刪除,但一個它在,除非它是線程更少(由於具有成品其線程)。以下必須持有:

Q_ASSERT(!object->thread() || object->thread() == QThread::currentThread()); 
delete object; 

在有一個線程對象的情況下,你需要調用對象的方法deleteLater。刪除將在線程的事件循環內完成。當對象被刪除時,是時候完成線程了。所以:

if (my_class->thread()) { 
    connect(my_class, SIGNAL(destroyed()), thread, SLOT(quit()); 
    my_class->deleteLater(); 
} else { 
    delete my_class; // It's a threadless object, we can delete it 
    thread->quit(); 
} 
thread->wait(); 

注意,它是確定調用quit()wait()上完成一個線程。像你一樣檢查正在運行的線程是多餘的。

+0

。我嘗試過,但ID不輸入my_class析構函數 – barp