我在主函数中有一个事件循环,在其中我想创建一个对象并在该对象的成员函数上运行一个线程。然而,我注意到对象在线程开始之前就被销毁了。我不明白为什么。
我的代码:
#include <iostream>
#include <thread>
class MyClass {
public:
MyClass(){
std::cout << "MyClass constructor is called" << std::endl;
}
~MyClass(){
std::cout << "MyClass destructor is called" << std::endl;
}
void start(){
std::cout << "MyClass is starting" << std::endl;
}
};
int main()
{
MyClass mine;
std::thread t(&MyClass::start, mine);
t.join();
}
输出:
MyClass constructor is called
MyClass destructor is called
MyClass is starting
MyClass destructor is called
MyClass destructor is called
期望的输出:
MyClass constructor is called
MyClass is starting
MyClass destructor is called