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;
}
采用引用計數的方式進行管理,簡單明了