unique_ptr
template<class T>
class Unique_ptr
{
private:
T* ptr=NULL;
public:
Unique_ptr(Unique_ptr& u) = delete;
Unique_ptr& operator=(Unique_ptr& u) = delete;
Unique_ptr(T* p)
{
ptr = p;
cout << "构造" << endl;
}
Unique_ptr()
{
}
~Unique_ptr()
{
if (ptr)
{
delete ptr;
ptr = NULL;
cout << "析构" << endl;
}
}
Unique_ptr(Unique_ptr&& p)
{
ptr = p.ptr;
p.ptr = NULL;
}
Unique_ptr& operator=(Unique_ptr&& p)
{
if(this!=&p){
ptr = p.ptr;
p.ptr = NULL;
}
return *this;
}
T* operator->()
{
return ptr;
}
T& operator*()
{
if (ptr)
{
return *ptr;
}
T a = -1;
return a; }
};
shared_ptr
template <typename T>
class myshared_ptr
{
public:
myshared_ptr(T* value)
{
ptr = value;
count++;
}
myshared_ptr(const myshared_ptr& m) {
ptr = m.ptr;
count = m.count;
count++;
}
myshared_ptr& operator=(const myshared_ptr& m) {
if (this != &m) {
ptr = m.ptr;
count = m.count;
count++;
}
return *this;
}
T& operator->() {
return this->ptr;
}
~myshared_ptr() {
count--;
if (this->count== 0) {
delete ptr;
cout << "释放内存空间" << endl;
}
}
public:
T* ptr;
static int count;
};
template <typename T>
int myshared_ptr<T>::count = 0;