使用线程销毁类析构函数中的shared_ptr成员变量
Destroying a shared_ptr member variable in the class destructor using a thread
我正在尝试使用thread
重新创建销毁bar
类析构函数中的shared_ptr成员变量,我认为这可能是堆损坏的原因。我个人觉得在析构函数中使用线程很奇怪,所以我希望 SO 的意见。
指针可能比应用程序寿命更长,所以使用detach
更可取。如果使用detach
则不调用析构函数,但如果join
,则它可以工作。
1(以这种方式重置智能指针是错误的吗?
2( 为什么在使用std::thread::detach()
时不调用析构函数?
#include <iostream>
#include <thread>
#include <memory>
#include <chrono>
using namespace std;
class foo
{
public:
foo(){longcomputation();}
void longcomputation()
{
std::cout<<" long computation called n";
std::this_thread::sleep_for(std::chrono::seconds(1));
}
};
class bar
{
public:
bar(): foo_(std::make_shared<foo>()) {}
~bar()
{
std::thread([foo = std::move(foo_)] () mutable
{
foo.reset();
std::cout<<" bar dctor called n";
}).detach(); // ==========> works with join however
}
private:
std::shared_ptr<foo> foo_;
};
int main()
{
bar bar1;
std::this_thread::sleep_for(std::chrono::seconds(3));
std::cout << "Exitingn";
}
这
看起来确实是处理线程和智能指针的糟糕方法,虽然我不是C++大师,但我会说这是一种糟糕的编码方式C++整体(几乎肯定会存在可读性可维护性等问题(。
来到析构函数,在调度分离的线程之前,析构函数退出,销毁foo_
对象,因此std::move(foo_)
失败。当你使用 join()
而不是 detach()
,你正在使析构函数等待线程,这就是它工作的原因。如果我们在分离线程后在析构函数中构建睡眠,它也会起作用:
~bar()
{
std::thread([foo = std::move(foo_)] () mutable
{
foo.reset();
std::cout<<" bar dctor called n";
}).detach(); // ==========> works with join however
// this works too
std::this_thread::sleep_for(std::chrono::seconds(1));
}
相关文章:
- CLANG 编译器 说:变量"PTR"可能未初始化
- 在以唯一ptr为值的C++映射中,动态内存何时会被销毁
- 将 ptr 传递给 ptr 到 A 作为参数传递给 A 的函数是不好的做法吗?
- 为共享 ptr 向量实现复制 c'tor?
- 字符和整数中 **(ptr+1) 的值差异
- C++:在不中断共享的情况下通过引用传递共享 PTR?
- 如何将派生类从基 ptr 分配给 nlohmann::json
- 引用 std::shared:ptr 以避免引用计数
- 为什么我不能在不进行任何转换的情况下将浮点数放入任何类型的 ptr 中?
- 在调用函数时,ptr** 和 ptr*& 之间是否有区别,或者首选C++?
- 另一种类型的智能ptr,比如具有弱refs的unique_ptr
- 尝试打印出 *ptr++ 的值,以了解它是如何工作的
- 如何控制共享 ptr 引用计数?
- dopen():不以 root 身份运行时"failed to map segment from shared object"
- C++中的指针否定 (!ptr == NULL)
- 从const ptr*转换为ptr*时出现问题
- 无法使用 libtool 将 -shared 参数传递给 g++
- boost::shared_ptr和std::shared-ptr的同居
- 我可以用std::shared_ptr而不是boost::shared-ptr构建boost库吗
- shared-ptr-C++shared_ptr与unique_ptr用于资源管理