温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

仿函数,()的重载

发布时间:2020-07-26 21:18:57 来源:网络 阅读:165 作者:be_better_ 栏目:编程语言

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

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;
}
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI