线程安全指针实现如下:
#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
#