2016-11-16 16 views
0

我正在學習C++中的線程。這裏是小片段我有什麼私下作出─我已經啓動了線程,但它調用了許多次析構函數,爲什麼?

#include<thread> 
#include<iostream> 

struct tes { 

//Constructor 
tes() { 
    std::cout << "Constructor\n"; 
} 

//Destructor 
virtual ~tes() { 
    std::cout << "Destructor\n"; 
} 

void operator()() { 
    for(int i = 0 ; i < 15 ; ++i) std::cout << "Hello\n"; 
} 

}; 
typedef struct tes TES; 
// Method 

void Input() { 
    TES t1;        //Line #1 
    //t1();        //Line #2 
    std::thread thr_1(t1);    //Line #3 
    thr_1.join();      //Line #4 
    //thr_1.detach();     //Line #5 
} 

//main() 

int main(){ 
    Input();      //calling this with parameters 
    //... 
} 

在上述功能Input(),如果我打電話只是#1和#2,一切運行良好。而如果我正在嘗試#1,#3,#4(或#5),則輸出相當混亂。析構函數調用了很多次,我不明白爲什麼?請幫幫我。謝謝!!

//輸出

Constructor 
Destructor 
Hello 
Hello 
Hello 
Hello 
Hello 
Hello 
Hello 
Hello 
... 
Destructor 
Destructor 
Destructor 
Destructor 
+0

我的不好,typedef丟失。 @CraigYoung –

+0

先生,唯一的問題是我手動輸入它,讓我檢查它@ @ CraigYoung –

+0

這就是爲什麼我說複製+粘貼...它避免了所有手動輸入錯誤。這是對每個人時間的不必要的浪費 - 包括你的! –

回答

0

這是輸出運行你的代碼後,我得到(ofcourse固定之後):

 
Constructor 
Destructor 
Hello 
Hello 
Hello 
Hello 
Hello 
Hello 
Hello 
Hello 
Hello 
Hello 
Hello 
Hello 
Hello 
Hello 
Hello 
Destructor 
Destructor 

析構函數被調用了三次:

  1. 從您在INPUT功能中創建的t1對象。 [最後一個]

  2. thread的構造函數複製後,您可以在bind期間調用。 [第一個打印]

  3. 當線程本身完成,從而調用被複制的可調用對象的析構函數。 [第二最後]

+0

謝謝,進行編輯。可能是它的編譯器依賴。我使用VS 2013和它調用析構函數5次。 –

+0

如何以及爲什麼?謝謝! –

+0

是的,它的編譯器依賴它,主要取決於如何實現bind,並依賴於優化設置。如果提升優化級別(如果尚未完成),則可能會看到更少的析構函數調用。 – Arunmu

相關問題