仿函數,()的重載

以智能指針爲例說明,具體看註釋:

template<class T>
class DFDef
{
public:
    void operator()(T*& p)//()的重載,只需要接受一個T類型對象的指針
    {
        if (p)
        {
            delete p;
            p = nullptr;
        }
    }
};

template<class T>
class Free
{
public:
    void operator()(T*& p)
    {
        if (p)
        {
            free(p);
            p = nullptr;
        }
    }
};

class FClose
{
public:
    void operator()(FILE*& p)
    {
        if (p)
        {
            fclose(p);
            p = nullptr;
        }
    }
};

namespace bite
{
    template<class T, class DF = DFDef<T>>//DF是一個自定義類型模板,默認調用DFDef
    class unique_ptr
    {
    public:
        // RAII
        unique_ptr(T* ptr = nullptr)
            : _ptr(ptr)
        {}

        ~unique_ptr()
        {
            if (_ptr)
            {
                //delete _ptr; // 釋放資源的方式固定死了,只能管理new的資源,不能處理任意類型的資源
                //DF()(_ptr);
                DF df;//創建一個DF對象
                df(_ptr);//調用df中的()重載,傳入指針
                _ptr = nullptr;
            }
        }

        // 具有指針類似行爲
        T& operator*()
        {
            return *_ptr;
        }

        T* operator->()
        {
            return _ptr;
        }

        unique_ptr(const unique_ptr<T>&) = delete;  // 1. 釋放new的空間  2.默認成員函數 = delete : 告訴編譯器,刪除該默認成員函數
        unique_ptr<T>& operator=(const unique_ptr<T>&) = delete;

    private:
        T* _ptr;
    };
}

#include<malloc.h>
void TestUniquePtr()
{
    //通過模板參數列表的第二個參數,選擇在析構時選擇對應的析構方法
    bite::unique_ptr<int> up1(new int);
    bite::unique_ptr<int, Free<int>> up2((int*)malloc(sizeof(int)));//傳一個類進去
    bite::unique_ptr<FILE, FClose> up3(fopen("1.txt", "w"));
}

int main()
{
    TestUniquePtr();
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章