当前位置:网站首页>初探智能指针之std::shared_ptr、std::unique_ptr
初探智能指针之std::shared_ptr、std::unique_ptr
2022-04-23 06:14:00 【CS生】
什么是智能指针、作用
智能指针用于确保当对象不再使用时对象可以被自动删除。
std::shared_ptr
几个指针能共享地指向同一个对象,当没有指针指向这个对象时,该对象会被删除(析构)。
// std::shared_ptr<MyTime> mt0 = new MyTime(0, 70); // error 类型不匹配
// MyTime* mt0 = std::make_shared(1, 70); // error 类型不匹配
std::shared_ptr<MyTime> mt1(new MyTime(10));
std::shared_ptr<MyTime> mt2 = mt1; // mt2和mt1指向同一个对象
auto mt1 = std::make_shared<MyTime>(1, 70); // C++17
std::unique_ptr
与std::shared_ptr不同,一个std::unique_ptr会指向一个对象且不允许其他指针指向。
std::unique_ptr<MyTime> mt1(new MyTime(10));
std::unique_ptr<MyTime> mt2 = std::make_unique<MyTime>(80); // C++17
但是,一个被std::unique_ptr指向的对象可以被move到另一个指针指向。
std::unique_ptr<MyTime> mt3 = std::move(mt1);
如何理解智能指针
智能指针的类型本质上是模板类,所以智能指针是对象,具有生命周期,当生命周期结束时,智能指针会销毁调用析构函数。
例如:std::shared_ptr的析构函数会对指向对象的指针数量减1,当没有指向该对象的指针时,对象内存销毁。
版权声明
本文为[CS生]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_36824130/article/details/123487614
边栏推荐
猜你喜欢
Visual Studio 2019安装与使用
【点云系列】PnP-3D: A Plug-and-Play for 3D Point Clouds
Unwind 栈回溯详解
主流 RTOS 评估
Raspberry Pie: two color LED lamp experiment
UEFI学习01-ARM AARCH64编译、ArmPlatformPriPeiCore(SEC)
【点云系列】Unsupervised Multi-Task Feature Learning on Point Clouds
GIS实用小技巧(三)-CASS怎么添加图例?
1.1 PyTorch和神经网络
【指标】Precision、Recall
随机推荐
C language, a number guessing game
第2章 Pytorch基础2
【动态规划】最长递增子序列
Pymysql connection database
【点云系列】Relationship-based Point Cloud Completion
【3D形状重建系列】Implicit Functions in Feature Space for 3D Shape Reconstruction and Completion
画 ArcFace 中的 margin 曲线
直观理解 torch.nn.Unfold
AUTOSAR从入门到精通100讲(八十一)-AUTOSAR基础篇之FiM
Pytoch model saving and loading (example)
. net encountered failed to decode downloaded font while loading font:
安装 pycuda 出现 PEP517 的错误
【点云系列】Pointfilter: Point Cloud Filtering via Encoder-Decoder Modeling
【点云系列】PnP-3D: A Plug-and-Play for 3D Point Clouds
MySQL数据库安装与配置详解
【動態規劃】不同路徑2
【动态规划】杨辉三角
SHA512/384 原理及C语言实现(附源码)
多机多卡训练时的错误
torch.where能否传递梯度