C++ unique_ptr

基本用法

创建 std::unique_ptr

创建一个 std::unique_ptr 实例,可以通过显式调用构造函数:

#include <memory> std::unique_ptr<int> myPtr(new int(10)); // Okay

禁止复制

std::unique_ptr 禁止复制,因为它是独占所有权的智能指针,这保证了资源不会被多个指针共享:

#include <memory> std::unique_ptr<int> myPtr(new int(10)); std::unique_ptr<int> myOtherPtr = myPtr; // 错误:不能复制 unique_ptr

使用移动语义

std::unique_ptr 支持 C++11 的移动语义,通过 std::move 可以将资源的所有权从一个 unique_ptr 转移到另一个 unique_ptr

#include <memory> #include <utility> // for std::move std::unique_ptr<int> myPtr(new int(10)); // Okay std::unique_ptr<int> myOtherPtr = std::move(myPtr); // Okay, 资源现在在 myOtherPtr 中

现在 myPtr 不再拥有资源,并且变为空(没有指向任何对象)。<

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

**K

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值