RAII std::unique_ptr

 1.先了解一下std::unique_ptr使用。

// 初级
void test_unique_ptr_basic()
{
    // 错误1
    //std::unique_ptr a;
    
    // 错误2
    //std::unique_ptr a{ new int };
    
    // 未分配内存
    std::unique_ptr<int> a;
    if (a)
    {
        std::cout << "a is allocated: " << *a << std::endl;
    }
    else
    {
        std::cout << "a is nullptr, not yet allocated" <<std::endl;
    }
}
void test_unique_ptr_okay()
{
    // 分配内存,但未初始化
    std::unique_ptr<int> a{ new int };

    if (a)
    {
        std::cout << "a is allocated, its value: " << *a << std::endl;
    }
    else
    {
        std::cout << "a is not yet allocated." << std::endl;
    }
}
void test_unique_ptr_whit_initial_value()
{
    // 分配内存,并初始化
    std::unique_ptr<int> a{ new int{} };

    if (a)
    {
        std::cout << "a is allocated, its value: " << *a << std::endl;
    }
    else
    {
        std::cout << "a is not yet allocated." << std::endl;
    }
}

2.步入正题RAII。

void test_unique_ptr_with_raii_one()
{
    int value = 5;
    auto my_deleter = [](auto p) // 这里 p 类型为 int* (auto 可以替换成int*)
    {
        std::cout << "not delete p" << std::endl;
    };
    std::unique_ptr<int> a{ &value, my_deleter };
}
void test_unique_ptr_with_raii_two()
{
    int value = 5;
    
    struct my_deleter
    {
        void operator()(int* p)
        {
            std::cout << "not delete p: " << *p << std::endl;
        }
    };
    
    // 这里可以省略my_deleter{},因为struct拥有默认构造函数。
    std::unique_ptr<int, my_deleter> a{ &value/*, my_deleter{}*/ };
    
}
namespace hoo
{
    struct my_deleter
    {
        template<typename T>
        void operator()(T p)
        {
            std::cout << "call my_deleter" << std::endl;
        }
    };
}

void test_unique_ptr_with_raii_three()
{
    int value = 5;
    std::unique_ptr<int, hoo::my_deleter> a{ &value };
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值