Placing the 'thread' code inside overloaded function 'operator()', seems to result in the destructor being called first thing.
Stepping through it in the debugger it looks like literally the first step in the thread is to call the destr.
So the question is, how to place an object into a thread without the destr being called right off the bat.
Here is a program showing 4 ways to place the object in a thread. All of them call the destr prior to the object being used (the 4th way calls it twice).
Note: Using approach number 3, it also does it even if operator() isn't the overloaded function.
#include <iostream>
#include <thread>
#include <unistd.h>
class MyClass {
private: int m_id;
public:
//constr
MyClass(int id) { m_id=id; std::cout << "constr_" << m_id << "\n";}
//destr
~MyClass() { std::cout << "destr_" << m_id << "\n"; }
//operator () override for thread
void operator()() {
while(true) {
std::cout << m_id << "\n";
sleep(1);
}
}
};
int main(int argc, char **argv) {
MyClass m1(1);
MyClass m2(2);
MyClass m3(3);
std::thread thread1 { m1 };
std::thread thread2(m2);
std::thread thread3(&MyClass::operator(), m3);
std::thread thread4{ MyClass(4) };
thread1.join();
return 0;
}
Aucun commentaire:
Enregistrer un commentaire