阅读背景:

线程安全智能指针实现(引用计数)_三体问题_智能指针引用计数怎么实现的线程安全

来源:互联网 

   线程安全指针实现如下:

  

#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();
        }

        _count = ptr._count.load(std::memory_order_seq_cst);
        _p = ptr._p;
        ++_count;

        return *this;
    }

    PTR& get_value()
    {
        assert(this->_p != nullptr);
        return *(this->_p);
    }

    PTR* get_value_ptr()
    {
        assert(this->_p != nullptr);
        return this->_p;
    }

private:
    std::atomic<int> _count;
    PTR *_p;
};

#endif // !INTELLECT_PTR_H#ifndef INTELLECT_PTR_H
#



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: