C++线程安全的智能指针

smart_ptr.hpp

复制代码

#pragma once
#include <cstdint>
#include <memory>

template <class T>
class smart_ptr {
private:
T* _obj;
uint32_t _count;
protected:
public:
smart_ptr(T* obj_);
smart_ptr(const smart_ptr&);
smart_ptr& operator =(const smart_ptr&);
void operator =(void*);
T* operator ->();
~smart_ptr();

void add();
void dec();
uint32_t count();
};

template <class T>
inline smart_ptr<T>::smart_ptr(T* obj_) : _obj(obj_), _count(1) {}

template <class T>
inline smart_ptr<T>::smart_ptr(const smart_ptr& that) : _count(0) {
if (that._count == 0) {
return;
}
memcpy_s(this, sizeof(smart_ptr), &that, sizeof(smart_ptr));
add();
}

template <class T>
inline smart_ptr<T>& smart_ptr<T>::operator =(const smart_ptr& that) {
if (&that == this || that._count == 0) {
return *this;
}
dec();
memcpy_s(this, sizeof(smart_ptr), &that, sizeof(smart_ptr));
add();
return *this;
}

template<class T>
inline void smart_ptr<T>::operator=(void* other) {
dec();
}

template<class T>
inline T* smart_ptr<T>::operator->() {
return _obj;
}

template <class T>
inline smart_ptr<T>::~smart_ptr() {
dec();
}

template <class T>
inline void smart_ptr<T>::add() {
_MT_INCR(_count);
}

template <class T>
inline void smart_ptr<T>::dec() {
if (_MT_DECR(_count) == 0) {
delete _obj;
}
}

template <class T>
inline uint32_t smart_ptr<T>::count() {
return _count;
}

复制代码

采用引用计数的方式进行管理,简单明了

posted @   Muzzik  阅读(1369)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起