Created
July 18, 2017 02:04
-
-
Save chenyahui/2f0d2b2a7420d5d64840c8be1ae2bbc5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
namespace cyh { | |
template<class T> | |
class SmartPtr; | |
template <typename T> | |
class U_Ptr; | |
template <typename T> | |
class U_Ptr | |
{ | |
private: | |
friend class SmartPtr<T>; | |
U_Ptr(T *ptr) :p(ptr), count(1) { } | |
~U_Ptr() { delete p; } | |
int count; | |
T *p; | |
}; | |
template<class T> | |
class SmartPtr | |
{ | |
public: | |
typedef SmartPtr<T> _Myt; | |
SmartPtr() = delete; | |
constexpr SmartPtr(std::nullptr_t) | |
{} | |
SmartPtr(_Myt& Value) : pointer(Value.pointer) | |
{ | |
Value.pointer->count++; | |
} | |
SmartPtr(T *p) : pointer(new U_Ptr<T>(p)) | |
{ | |
} | |
SmartPtr& operator=(_Myt& _Right) | |
{ | |
reduce(); | |
this->pointer = _Right.pointer; | |
this->pointer->count++; | |
return *this; | |
} | |
T* operator->() | |
{ | |
return pointer; | |
} | |
T& operator*() | |
{ | |
return *pointer; | |
} | |
int use_count() const | |
{ | |
return this->pointer->count; | |
} | |
T* get() | |
{ | |
return pointer; | |
} | |
~SmartPtr() | |
{ | |
reduce(); | |
} | |
private: | |
void reduce() { | |
if (--this->pointer->count == 0) { | |
delete this->pointer; | |
} | |
} | |
U_Ptr<T> *pointer; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment