c++ 中的智能指针实现
摘要:C++11 中新增加了智能指针来预防内存泄漏的问题,在 share_ptr 中主要是通过“引用计数机制”来实现的。我们今天也来自己实现一个简单的智能指针:

1 // smartPointer.cpp : 定义控制台应用程序的入口点。 2 // 3 4 #include "stdafx.h" 5 #include <iostream> 6 #include<windows.h> 7 8 using namespace std; 9 10 11 class Person 12 { 13 public: 14 Person(){ count = 0; }; 15 ~Person() { }; 16 void inc(){ count++; } 17 void dec(){ count--; } 18 int getCount(){ return count; } 19 void printInfo() { 20 cout << "just a test function" << endl; 21 } 22 23 private: 24 int count; // 增加类的计数成员,在执行智能指针对象的析构函数时,进行判断是否要 delete 这个对象 25 }; 26 27 28 class smartPointer 29 { 30 public: 31 smartPointer(){ p = nullptr; }; 32 smartPointer(Person *other); // 带参构造函数 33 smartPointer(smartPointer &other) { // 拷贝构造函数 34 p = other.p; 35 p->inc(); 36 } 37 Person *operator->() { // 重载 -> 38 return p; 39 } 40 Person& operator*() { // 重载 * 41 return *p; 42 } 43 44 ~smartPointer(); 45 private: 46 Person *p; 47 }; 48 49 smartPointer::smartPointer(Person *other) { 50 cout << "Person()" << endl; 51 p = other; 52 p->inc(); 53 } 54 55 smartPointer::~smartPointer() 56 { 57 cout << "~Person()" << endl; 58 if (p) { 59 p->dec(); 60 if (p->getCount() == 0) { 61 delete p; 62 p = nullptr; 63 }// if 64 }//if 65 } 66 67 void test_func(smartPointer& other) { 68 smartPointer s = other; 69 s->printInfo(); 70 } 71 72 73 int _tmain(int argc, _TCHAR* argv[]) 74 { 75 smartPointer sp = new Person(); // 调用带参构造函数( sp 对象中的指针 p 指向构造的 Person 对象) 76 (*sp).printInfo(); 77 78 system("pause"); 79 return 0; 80 }
所有博文均为原著,如若转载,请注明出处!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗