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

采用引用計數的方式進行管理,簡單明了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM