5种智能指针指向数组的方法| 5 methods for c shared_ptr point to an array

本文介绍了在C++中使用shared_ptr管理动态分配数组的5种正确方法,包括如何设置自定义 deleter,以及内置的数组支持。详细代码示例和解释确保了资源的正确释放。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文首发于个人博客https://kezunlin.me/post/b82753fc/,欢迎阅读最新内容!

5 methods for c shared_ptr point to an array

Guide

shared_ptr

Prior to C 17, shared_ptr could not be used to manage dynamically allocated arrays. By default, shared_ptr will call delete on the managed object when no more references remain to it. However, when you allocate using new[] you need to call delete[], and not delete, to free the resource.

In order to correctly use shared_ptr with an array, you must supply a custom deleter.

code example

//OK, pointer to int 999
std::shared_ptr<int> sp(new int(999)); 


template< typename T >
struct array_deleter
{
  v
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值