c++ - 为什么类成员包含 "std::shared_ptr<std::thread>"时会发生崩溃?

标签 c++ pointers shared

我发现当类成员包含“std::shared_ptr”时,我的应用程序会崩溃。例如:

#include <thread>
#include <memory>

class Derived {
public:
    Derived() {
        mThread = std::make_shared<std::thread>(&Derived::callback, this);
    }
    ~Derived() { }

    void callback() {}

    int add(int x, int y) { return x + y; }

private:
    std::shared_ptr<std::thread> mThread;
};

int main() {
    Derived * base = new Derived();
    delete base;
    return 0
}

我想知道为什么?

最佳答案

当您启动线程时,您必须在调用线程的析构函数之前加入分离 它们。我建议在析构函数中执行此操作:

#include <thread>
#include <memory>

class Derived
{
public:
    Derived()
    {
        mThread = std::make_shared<std::thread>(&Derived::callback, this);
    }
    ~Derived()
    {
        if(mThread->joinable())
            mThread->join();
    }
    void callback() {}
    int add(int x, int y) { return x + y; }
private:
    std::shared_ptr<std::thread> mThread;
};

int main()
{
    Derived * base = new Derived();
    delete base;
    return 0;
}

顺便说一下,在你的例子中使用 shared_ptr 是没有必要的。您可以简单地定义 thread 变量:

thread mThread;

开始新线程:

mThread = std::thread(&Derived::callback, this);

并在需要时加入它:

mThread.join();

关于c++ - 为什么类成员包含 "std::shared_ptr<std::thread>"时会发生崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53512987/

相关文章:

C++ 在使用 .o 和使用 .a 文件链接之间存在差异 : different behavior, 为什么?

directx - 在 DirectX 11 和 DirectX 10 之间共享纹理

git - 如何配置现有的 git repo 以供 UNIX 组共享

c++ - OpenCV 3.2.0 iOS 类型转换 : int to __CLPK_integer *

c - 尝试将指针移交给函数时如何修复 'expected * but argument is of type **' 错误

c - 指向自定义地址

c++ - 如何正确地使一个对象拥有另一个多态对象?

c++ - 优化模板代码编译

c++ - 多语言编译中的I/O问题

c++ - 调用另一个exe并获取值