在成员函数上启动线程时不需要的析构函数调用
Undesirable destructor call when starting a thread on a member function
我的主函数中有一个事件循环,我想在其中创建一个对象并在对象的成员函数上运行一个线程。但是,我注意到该对象甚至在线程启动之前就被销毁了。我不明白为什么。
我的代码:
#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
通过
引用传递mine
:std::thread t(&MyClass::start, std::ref(mine));
mine
的类型是 MyClass
,这意味着你按值传递它。因此std::thread
将其副本传递给新创建的线程。
您需要明确告知模板您要通过引用传递mine
。
std::thread
内部创建本地对象并多次调用复制构造函数,并在使用后销毁本地对象。因此,您将获得多个输出作为MyClass destructor is called
。如果要检查对象构造的行为,则可以在类中包含复制构造函数。
相关文章:
- 为什么这里不调用析构函数
- 如果我也使用复制构造函数并且重载 = 运算符,我是否需要析构函数?
- 为什么在运算符删除中不调用析构函数?
- 如果引用应该保留,不删除析构函数中的指针会导致内存泄漏吗?
- 单例:为什么不需要删除并且看不到析构函数调试消息
- 为什么移动运算符不只是析构函数+移动构造函数
- 我不明白析构函数有什么问题?
- 从 std::streambif 继承时不兼容析构函数编译器警告
- 可观察行为和未定义行为 -- 如果我不调用析构函数会发生什么?
- 为什么C++ std::list::clear() 不调用析构函数
- 需要析构函数来释放内存空间,即使所有项目都已弹出
- c++中的Guard,在main中未处理异常时不调用析构函数
- 删除类数组而不调用析构函数
- 您是否需要析构函数来销毁全局 int、float 或 std::string 变量
- 移动构造函数不调用析构函数
- 删除 void 指针时不调用析构函数
- 为什么在删除析构函数时调用析构函数,如果未删除则不调用析构函数?
- 在构造函数中引发异常时不调用析构函数
- 为什么在数组创建期间抛出未捕获的异常时不调用析构函数C++?
- 为什么noexcept构造函数需要析构函数的实例化