当前位置:网站首页>初探智能指针之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
边栏推荐
猜你喜欢
FATFS FAT32学习小记
【点云系列】DeepMapping: Unsupervised Map Estimation From Multiple Point Clouds
WinForm scroll bar beautification
第2章 Pytorch基础2
UEFI学习01-ARM AARCH64编译、ArmPlatformPriPeiCore(SEC)
Visual studio 2019 installation and use
[3D shape reconstruction series] implicit functions in feature space for 3D shape reconstruction and completion
Résolution du système
Write a wechat double open gadget to your girlfriend
EasyUI combobox determines whether the input item exists in the drop-down list
随机推荐
第5 章 机器学习基础
Chapter 2 pytoch foundation 2
SSL / TLS application example
利用官方torch版GCN训练并测试cora数据集
torch.mm() torch.sparse.mm() torch.bmm() torch.mul() torch.matmul()的区别
[point cloud series] sg-gan: advantageous self attention GCN for point cloud topological parts generation
免费使用OriginPro学习版
【期刊会议系列】IEEE系列模板下载指南
Summary of image classification white box anti attack technology
PyTorch 20. PyTorch技巧(持续更新)
主流 RTOS 评估
Infrared sensor control switch
【動態規劃】不同路徑2
[dynamic programming] different paths 2
【点云系列】点云隐式表达相关论文概要
Visual Studio 2019安装与使用
PyTorch最佳实践和代码编写风格指南
【点云系列】SG-GAN: Adversarial Self-Attention GCN for Point Cloud Topological Parts Generation
Machine learning III: classification prediction based on logistic regression
图像分类白盒对抗攻击技术总结