std::unique_ptr、std::shared_ptr定制删除器

1. 给std::unique_ptr定制删除器

1.1 方法一,使用functor

#include <iostream>
#include <memory>
#include <stdio.h>

struct FileCloser{
    void operator()(FILE* fp) const{
        fclose(fp);
        fp = nullptr;

        std::cout << "file automatically closed.\n";
    }
};

auto main()->int {
    std::unique_ptr<FILE, FileCloser> pfile(fopen("1.txt", "w"));
}

1.2 方法二,使用函数指针

#include <iostream>
#include <memory>
#include <stdio.h>

auto main()->int{
    // 删除器可修改,但指针大小增长一倍
    std::unique_ptr<FILE, void(*)(FILE*)> pfile(fopen("2.txt", "w"), [](FILE* pf){fclose(pf); pf = nullptr; std::cout << "file automatically closed.\n";});
}

1.3 方法三,使用未求值的lambda

#include <iostream>
#include <memory>
#include <stdio.h>

auto main()->int{
    // 未求值的lambda,g++ main.cpp -std=c++20
    // 适合单次使用,不适合做接口,因为lambda表达式在每次使用都属于不同的类型
    std::unique_ptr<FILE, decltype([](FILE* fp){fclose(fp); fp = nullptr; std::cout << "file auto closed.\n";})> pfile(fopen("3.txt", "w"));
}
}

2. 给std::shared_ptr定制删除器

2.1 方法一

#include <iostream>
#include <memory>
#include <stdio.h>

struct FileCloser{
    void operator()(FILE* fp) const{
        fclose(fp);
        fp = nullptr;

        std::cout << "file automatically closed.\n";
    }
};

auto main()->int {
    std::shared_ptr<FILE> pfile(fopen("1.txt", "w"), FileCloser());
}

2.2 方法二

#include <iostream>
#include <memory>
#include <stdio.h>

auto main()->int{
    std::shared_ptr<FILE> pfile(fopen("2.txt", "w"), [](FILE* pf){fclose(pf); pf = nullptr; std::cout << "file automatically closed.\n";});
}

2.3 方法三

#include <iostream>
#include <memory>
#include <stdio.h>

auto main()->int{
    std::shared_ptr<FILE> pfile(fopen("3.txt", "w"), [](FILE* fp){
        if(fp){fclose(fp); fp = nullptr;} std::cout << "file auto closed.\n";});
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值