线程安全指针实现如下:
#ifndef INTELLECT_PTR_H
#define INTELLECT_PTR_H
#include <atomic>
#include <assert.h>
template <class PTR >
class interllect_ptr
{
public:
interllect_ptr()
{
if (_p == nullptr)
{
_p = new PTR();
++_count;
}
}
~interllect_ptr()
{
--_count;
if (_count == 0)
{
delete _p;
_p = nullptr;
}
}
interllect_ptr(const interllect_ptr& ptr)
{
if (this != &ptr)
{
_p = ptr._p;
_count = ptr._count.load(std::memory_order_seq_cst); // 可疑代码段,不安全根源
++_count;
}
}
interllect_ptr& operator= (const interllect_ptr &ptr)
{
if (this == ptr)
{
return *this;
}
if (_p != nullptr)
{
this->~interllect_ptr();

本文介绍了线程安全智能指针的实现,重点关注引用计数在多线程环境下的处理。通过测试代码展示,指针在被多个线程复制后能确保在所有线程完成时正确释放对象。尽管atomic对象不支持拷贝,但通过特定方式避免了问题。同时指出,智能指针仅保证了引用计数器的线程安全性,而指针所指向的数据并不保证线程安全。
最低0.47元/天 解锁文章
9184

被折叠的 条评论
为什么被折叠?



