C++11/14介绍(五)——智能指针和引用计数(二)

26 篇文章 0 订阅

std::shared_ptr

std::shared_ptr是一种智能指针,它能够记录多少个shared_ptr共同指向一个对象,从而消除显式的调用delete,当引用计数变为0时,就会将对象删除。

std::make_shared能够用来显式的使用new,所以std::make_shared会分配创建传入参数中的对象,并返回这个对象类型的std::shared_ptr指针,ex:

#include <iostream>
#include <memory>

void foo(std::shared_ptr<int> i)
{
    (*i)++;
}
int main()
{
    // auto pointer = new int(10); // 非法, 不允许直接赋值
    // 构造了一个 std::shared_ptr
    auto pointer = std::make_shared<int>(10);
    foo(pointer);
    std::cout << *pointer << std::endl; // 11

    // 离开作用域前,shared_ptr 会被析构,从而释放内存
    return 0;
}

std:;shared_ptr可以通过get()方法来获取原始指针,通过reset()来减少一个引用计数,并通过get_count()来查看一个对象的引用计数,ex:

#include <iostream>
#include <memory>

int main()
{
    auto pointer = std::make_shared<int>(10);
    auto pointer2 = pointer;    // 引用计数+1
    auto pointer3 = pointer;    // 引用计数+1
    int *p = pointer.get();             // 这样不会增加引用计数

    std::cout << "pointer.use_count() = " << pointer.use_count() << std::endl;      // 3
    std::cout << "pointer2.use_count() = " << pointer2.use_count() << std::endl;    // 3
    std::cout << "pointer3.use_count() = " << pointer3.use_count() << std::endl;    // 3

    pointer2.reset();
    std::cout << "reset pointer2:" << std::endl;
    std::cout << "pointer.use_count() = " << pointer.use_count() << std::endl;      // 2
    std::cout << "pointer2.use_count() = " << pointer2.use_count() << std::endl;    // 0, pointer2 已 reset
    std::cout << "pointer3.use_count() = " << pointer3.use_count() << std::endl;    // 2

    pointer3.reset();
    std::cout << "reset pointer3:" << std::endl;
    std::cout << "pointer.use_count() = " << pointer.use_count() << std::endl;      // 1
    std::cout << "pointer2.use_count() = " << pointer2.use_count() << std::endl;    // 0
    std::cout << "pointer3.use_count() = " << pointer3.use_count() << std::endl;    // 0, pointer3 已 reset
    return 0;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值