在成员函数上启动线程时不需要的析构函数调用

Undesirable destructor call when starting a thread on a member function

本文关键字:不需要 析构 函数调用 线程 成员 函数 启动      更新时间:2023-10-16

我的主函数中有一个事件循环,我想在其中创建一个对象并在对象的成员函数上运行一个线程。但是,我注意到该对象甚至在线程启动之前就被销毁了。我不明白为什么。

我的代码:

#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
通过

引用传递minestd::thread t(&MyClass::start, std::ref(mine));mine的类型是 MyClass ,这意味着你按值传递它。因此std::thread将其副本传递给新创建的线程。

您需要明确告知模板您要通过引用传递mine

std::thread内部创建本地对象并多次调用复制构造函数,并在使用后销毁本地对象。因此,您将获得多个输出作为MyClass destructor is called。如果要检查对象构造的行为,则可以在类中包含复制构造函数。