簡易實現unique_ptr智能指針

c++11的unique_ptr智能指針:
一旦創建,就指向那塊內存,以後再也不能讓其它的智能指針指向同一塊內存。
這個指針實現比較簡單,只需定義一個類的實例時,自己類內部刪除拷貝構造函數和刪除賦值運算符重載函數就可以了。

#include <iostream>
using namespace std;
template<typename T>
class munique_ptr{
    T *ptr;
    public:
    munique_ptr(T *_ptr=NULL):ptr(_ptr){}
    ~munique_ptr()
    {
        delete ptr;
    }
    //刪除拷貝構造函數
    munique_ptr(const munique_ptr &r)=delete;
    //刪除賦值運算符重載函數
    munique_ptr &operator=(const munique_ptr &r)=delete;

    T operator*()
    {
        return *ptr;
    }
};
int main(void)
{
    munique_ptr<double> ptr(new double(3.14));
    cout<<*ptr<<endl;
    munique_ptr<double> ptr1=ptr;
    munique_ptr<double> ptr2;
    ptr2=ptr;
}

因爲是unique_ptr指針,唯一的,如果存在兩個指針指向同一塊空間,那麼就會得一下運行結果:
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章