c – 在成员函数上启动线程时发出不需要的析构函数

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

我的代码

#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

解决方法

通过引用传递我的:std :: thread t(& MyClass :: start,std :: ref(mine));
我的类型是MyClass,这意味着你按值传递它.所以std :: thread将它的副本传递给新创建的线程.

你需要通过引用明确地告诉你通过我的模板.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...