unique_ptr一个会转移数据的智能指针

本文详细介绍了C++中的智能指针std::unique_ptr,包括其产生的原因,解决rawpointer的内存管理问题,以及其替代rawpointer、所有权转移等特性。通过实例展示了unique_ptr的常用操作,如move、release、reset和swap,并提供了源码实现的简单解析。文章还强调了unique_ptr不支持复制但支持移动的特性,确保了对象的唯一拥有权。

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

一、产生的原因:

unique_ptr的产生,就是为了解决,raw pointer 的new和delete配对使用问题。对于raw pointer来说,在new了之后,在delete之前往往会出现程序异常,进而导致delete没有被释放,如此以来就会产生内存泄漏。引入了unique_ptr之后,可以有效的减轻C++程序员对于raw pointer的使用负担。参考官方文档:

std::unique_ptr is a smart pointer that owns and manages another object through a pointer and disposes of that object when the unique_ptr goes out of scope.

https://en.cppreference.com/w/cpp/memory/unique_ptr

二、特性:

也正是因为上面的原因,unique_ptr具有两个特性:

特性1: 替代raw pointer,来封装对象,进行操作,不需要考虑内存泄漏,参考官方文档。

The object is disposed of, using the associated deleter when either of the following happens:

  • the managing unique_ptr object is destroyed

  • the managing unique_ptr object is assigned another pointer via operator= or reset().

https://en.cppreference.com/w/cpp/memory/unique_ptr

特性2: 具有ownership transfer的能力, 参考官方文档。

Only non-const unique_ptr can transfer the ownership of the managed object to another   unique_ptr.  If an object's lifetime is managed by a const std::unique_ptr, it is limited to the scope in which the pointer was created.

std::unique_ptr is commonly used to manage the lifetime of objects, including:

  • providing exception safety to classes and functions that handle objects with dynamic lifetime, by guaranteeing deletion on both normal exit and exit through exception

  • passing ownership of uniquely-owned objects with dynamic lifetime

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值