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 }
smartPointer
复制代码

 

参考博客:http://www.cnblogs.com/xiehongfeng100/p/4645555.html

posted on   爱笑的张飞  阅读(222)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示