加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 10:36:12 所属栏目:百科 来源:网络整理
导读:我的main函数中有一个事件循环,我想创建一个对象并在对象的成员函数上运行一个线程.但是,我注意到在线程启动之前对象被销毁了.我不明白为什么. 我的代码: #include iostream#include threadclass MyClass {public: MyClass(){ std::cout "MyClass construct
我的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将它的副本传递给新创建的线程.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读