template<typename T>
class auto_ptr {
public:
auto_ptr(T* ptr = nullptr) : _ptr(ptr) {
}
auto_ptr(auto_ptr<T>& ap) : _ptr(ap._ptr) {
ap._ptr = nullptr;
}
auto_ptr<T>& operator=(auto_ptr<T>& ap) {
if(this != &ap) {
if(_ptr) delete _ptr;
_ptr = ap._ptr;
ap._ptr = nullptr;
}
return *this;
}
~auto_ptr() {
delete _ptr;
}
T& operator*() {
return *_ptr;
}
T* operator->() {
return _ptr;
}
private:
T* _ptr;
};
template<typename T>
class unique_ptr {
public:
unique_ptr(T* ptr) : _ptr(ptr) {
}
unique_ptr(unique_ptr<T>& up) = delete;
unique_ptr<T>& operator=(const unique_ptr<T>& up) = delete;
~unique_ptr() {
delete _ptr;
}
T& operator*() {
return *_ptr;
}
T* operator->() {
return _ptr;
}
private:
T* _ptr;
};
template<typename T>
class shared_ptr;
template<typename T>
class Counter {
friend class shared_ptr<T>;
public:
Counter() : m_refCount(0) {
}
~Counter() {
}
Counter(const Counter&) = delete;
Counter<T>& operator= (const Counter<T>&) = delete;
private:
atomic_uint m_refCount;
};
template<typename T>
class shared_ptr {
public:
shared_ptr(T* ptr = nullptr) : _ptr(ptr), _cnts(new Counter<T>) {
if(_ptr) {
_cnts->m_refCount = 1;
}
}
shared_ptr(shared_ptr<T>& sp) : _ptr(sp._ptr), _cnts(sp._cnts) {
++_cnts->m_refCount;
}
shared_ptr<T>& operator=(const shared_ptr<T>& sp) {
if(this != &sp) {
if(--(_cnts->m_refCount) == 0 && _ptr) {
delete _ptr;
delete _cnts;
}
_ptr = sp._ptr;
_cnts = sp._cnts;
++_cnts->m_refCount;
}
return *this;
}
~shared_ptr() {
if((--_cnts->m_refCount) == 0 && _ptr) {
delete _ptr;
delete _cnts;
}
}
T& operator*() {
return *_ptr;
}
T* operator->() {
return _ptr;
}
int use_count() {
return _cnts->m_refCount;
}
T* get() {
return _ptr;
}
private:
Counter<T>* _cnts;
T* _ptr;
};
template<class T>
class weak_ptr{
public:
weak_ptr()
:_ptr(nullptr)
{}
weak_ptr(const weak_ptr<T>& wp)
:_ptr(wp._ptr)
{}
weak_ptr(const shared_ptr<T>& sp)
:_ptr(sp.get())
{}
weak_ptr<T>& operator= (const shared_ptr<T>& sp)
{
_ptr = sp.get();
return *this;
}
T& operator*()
{
return *_ptr;
}
T* operator->()
{
return _ptr;
}
private:
T* _ptr;
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)