std::unique_ptr 独占所有权智能指针

std::shared_ptr , 允许多个指针指向同一个对象

std::unique_ptr, 独占所指向的对象。

std::unique_ptr 是 c++11中用来取代 std::auto_ptr 指针的指针容器。 它不能与其他unique_ptr类型的指针对象共享所指对象的内存。这种所有权仅能够通过std::move函数来转移。unique_ptr是一个删除了拷贝构造函数、保留了移动构造函数的指针封装类型。

初始化quniue_ptr

std::unique_ptr<int> int_ptr(new int(10));

或者reset()

std::unique_ptr<int> int_ptr;
int*  test_pointer =  new int(10);
int_ptr.reset(test_pointer);

或者move 转换所有权

std::unique_ptr<int> int_ptr_1(new int(10));
std::unique_ptr<int> int_ptr;
int_ptr =  std::move(int_ptr_1);

释放原来对象的联系

调用release 会切断unique_ptr 和它原来管理的对象的联系。release 返回的指针通常被用来初始化另一个智能指针或给另一个智能指针赋值。如果不用另一个智能指针来保存release返回的指针,程序就要负责资源的释放。

release 释放对指针的控制权,返回指针,并将置为空。

#include <iostream>
#include <memory>

int main() {

       std::unique_ptr<int> uptr(new int(10));  //绑定动态对象
       //std::unique_ptr<int> uptr2 = uptr;  //不能賦值
       //std::unique_ptr<int> uptr2(uptr);  //不能拷内
       std::unique_ptr<int> uptr2 = std::move(uptr); //轉換所有權

       if(uptr == nullptr)
           printf("uptr give up *int\n");


       int * p = uptr2.release(); //uptr2释放对指针的控制权,返回指针,并将uptr2置为空

       if(uptr2 == nullptr)
         printf("uptr2 give up *int\n");


       printf("%d\n", *p);
       delete p;

       return 0;
}

输出结果:

uptr give up *int
uptr2 give up *int
10
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

蓝鲸123

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

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

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

打赏作者

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

抵扣说明:

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

余额充值