我正在學習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
我的不好,typedef丟失。 @CraigYoung –
先生,唯一的問題是我手動輸入它,讓我檢查它@ @ CraigYoung –
這就是爲什麼我說複製+粘貼...它避免了所有手動輸入錯誤。這是對每個人時間的不必要的浪費 - 包括你的! –