我发现当类成员包含“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/