c++智能指针
2021/8/3 22:07:57
本文主要是介绍c++智能指针,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
种类
- unique_ptr
- shared_ptr
- weak_ptr
shared_ptr实现
参考:https://www.jianshu.com/p/b6ac02d406a0
引用计数托管指针被引用的次数
简单实现:
#include <iostream> using namespace std; template<class T> class shared_ptr{ private: T* m_ptr; //被封装的指针 unsigned int shared_count; //引用计数,表示有多少个智能指针对象拥有m_ptr指向的内存块 public: shared_ptr(T* p):m_ptr(p),shared_count(1){ } ~shared_ptr() { deconstruct();} void deconstruct(){ if(shared_count == 1) //引用计数为1表示只有一个对象使用指针指向的内存块了 { delete m_ptr; m_ptr = 0; } shared_count--; } T& operator*() { return *m_ptr;} T* operator->() { return m_ptr;} //复制构造函数 shared_ptr(shared_ptr& sp):m_ptr(sp.m_ptr),shared_count(sp.shared_count){ shared_count++; } //重载运算符= shared_ptr& operator = (shared_ptr& sp){ sp.shared_count++; deconstruct(); //相当于先删掉左值,然后再通过右值赋值. m_ptr = sp.m_ptr; shared_count = sp.shared_count; return *this; } };
这篇关于c++智能指针的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-17zero-shot-learning-definition-examples-comparison
- 2024-06-06Package Easy(基于 NSIS 的打包exe安装包工具)使用方法-icode9专业技术文章分享
- 2024-06-06基于 casdoor 的 ELK 开源登录认证解决方案: elk-auth-casdoor-icode9专业技术文章分享
- 2024-05-29Elasticsearch慢查询日志配置
- 2024-05-29揭秘华为如此多成功项目的产品关键——Charter模板
- 2024-05-29海外IDC业务拓展的7大挑战
- 2024-05-29InLine Chat功能优化对标Github Copilot,CodeGeeX带来更高效、更直观的编程体验!
- 2024-05-29CodeGeeX 智能编程助手 6 项功能升级,在Visual Studio插件市场霸榜2周!
- 2024-05-29AutoMQ 生态集成 Apache Doris
- 2024-05-292024年IDC行业的深度挖掘:机遇、挑战与未来展望