#ifndef UNIQUE_PTR_H
#define UNIQUE_PTR_H
#include <stdio.h>
#include <iostream>
using namespace std;
// unique_ptr對象始終是關聯的原始指針的唯一所有者。
// 無法複製unique_ptr對象,它只能移動
template <typename T> // 泛型編程
class Unique_ptr
{
public:
explicit Unique_ptr(T* ptr = nullptr) : m_ptr(ptr)
{
}
~Unique_ptr()
{
delete m_ptr;
m_ptr = nullptr;
}
//不允許拷貝賦值,但可以移動
Unique_ptr(const Unique_ptr&) = delete ;
Unique_ptr& operator=(const Unique_ptr&) = delete ;
//移動構造函數,可以拷貝一個將要被銷燬的unique_ptr(右值引用,比如函數返回一個局部Unique_ptr對象
Unique_ptr(Unique_ptr && ptr)
{
m_ptr = ptr.m_ptr;
ptr.m_ptr = nullptr;
}
//移動賦值運算符,可以者賦值一個將要被銷燬的unique_ptr(右值引用)
Unique_ptr&operator=(Unique_ptr&& ptr)
{
if (this == &ptr) {
return *this;
}
if (m_ptr)
{
delete m_ptr;
}
m_ptr = ptr.m_ptr;
ptr.m_ptr = nullptr;
return *this;
}
public:
T* get() // 獲取內部對象的指針
{
return m_ptr;
}
T* release() //放棄內部對象的所有權,將內部指針置空,此指針需要手動釋放。
{
T* ptr = m_ptr;
m_ptr = nullptr;
return ptr;
}
void reset(T* ptr) //銷燬內部對象並接受新的對象的所有權
{
if(ptr != m_ptr)
{
if(m_ptr)
{
delete m_ptr;
m_ptr = nullptr;
}
m_ptr = ptr;
}
}
operator bool() const
{
return nullptr != m_ptr;
}
T& operator*()
{
return *m_ptr;
}
T* operator->()
{
return m_ptr;
}
private:
T* m_ptr;
};