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;
}
采用引用计数的方式进行管理,简单明了
本文来自博客园,作者:Muzzik,转载请注明原文链接:https://www.cnblogs.com/muzzik/p/12825136.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步