class Obj1 {
public:
Obj1(int input):input_(input) {
cout << __func__ << endl;
p = new int;
}
~Obj1() {
cout << __func__ << endl;
if (p != NULL) {
delete p;
p = NULL;
}
}
void operator()() {
cout << input_ << endl;
}
private:
int input_;
int* p;
};
int main(int argc, char** argv) {
thread t{Obj1{10}};
t.join();
return 0;
}
This code doesn't work as I imagine. Why Obj1's destructor should be called three times? And there'll be corruption because double free. How to fix this code?
Environment: Ubuntu 10.04.4 LTS, gcc4.7.2