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;
}

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

原文链接: https://www.cnblogs.com/muzzik/p/12825136.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

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

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/346151

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 上午3:45
下一篇 2023年3月2日 上午3:45

相关推荐