仿函数,()的重载

以智能指针为例说明,具体看注释:

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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章