Devesh Pratap Singh Devesh Pratap Singh - 17 days ago 6
C++ Question

I have started the thread but it's calling destructor numerous times, why?

I am learning threads in C++. Here is the small snippet what I have done-

#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
//...
}


In above function
Input()
, if I am calling only #1 and #2, everything is running fine. Whereas, if I am trying #1, #3 , #4(or #5 ), output is pretty messed up. Destructor calls itself numerous times and I am not getting why? please help me. THANKS!!

// output

Constructor
Destructor
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
...
Destructor
Destructor
Destructor
Destructor

Answer

This is the output I get after running your code (after fixing it ofcourse):

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

The destructor is called three times:

  1. From the t1 object you created in the function INPUT. [The last one]

  2. From the constructor of the thread after it copies you callable during bind. [The first print]

  3. When the thread itself finishes thereby calling the destructor of the copied callable. [The second last]

Comments