当前位置:网站首页>初探智能指针之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
边栏推荐
- PyTorch最佳实践和代码编写风格指南
- ECDSA 签名验证原理及C语言实现
- 【點雲系列】SG-GAN: Adversarial Self-Attention GCN for Point Cloud Topological Parts Generation
- [dynamic programming] different paths 2
- Android exposed components - ignored component security
- 【動態規劃】不同路徑2
- Pytoch model saving and loading (example)
- AUTOSAR从入门到精通100讲(八十三)-BootLoader自我刷新
- AUTOSAR从入门到精通100讲(五十)-AUTOSAR 内存管理系列- ECU 抽象层和 MCAL 层
- Chapter 4 pytoch data processing toolbox
猜你喜欢

【点云系列】Learning Representations and Generative Models for 3D pointclouds
Raspberry Pie: two color LED lamp experiment

Résolution du système

如何利用qemu搭建SOC protoype:80行代码实现一个Cortex M4 模拟器

【指标】Precision、Recall

ARMCC/GCC下的stack protector

Write a wechat double open gadget to your girlfriend

机器学习——PCA与LDA

1.1 PyTorch和神经网络

Wechat applet uses wxml2canvas plug-in to generate some problem records of pictures
随机推荐
AUTOSAR从入门到精通100讲(八十七)-高级EEA的关键利器-AUTOSAR与DDS
armv8m(cortex m33) MPU实战
EasyUI combobox determines whether the input item exists in the drop-down list
Pytoch model saving and loading (example)
PyTorch 17. GPU并发
AUTOSAR从入门到精通100讲(八十四)-UDS之时间参数总结篇
swin transformer 转 onnx
[dynamic programming] Yang Hui triangle
torch.where能否传递梯度
免费使用OriginPro学习版
【点云系列】FoldingNet:Point Cloud Auto encoder via Deep Grid Deformation
Minesweeping games
F.pad 的妙用
SHA512/384 原理及C语言实现(附源码)
GIS实战应用案例100篇(五十一)-ArcGIS中根据指定的范围计算nc文件逐时次空间平均值的方法
[3D shape reconstruction series] implicit functions in feature space for 3D shape reconstruction and completion
How keras saves and loads the keras model
PyTorch 13. 嵌套函数和闭包(狗头)
[point cloud series] pnp-3d: a plug and play for 3D point clouds
【點雲系列】SG-GAN: Adversarial Self-Attention GCN for Point Cloud Topological Parts Generation