我是靠谱客的博主 勤奋纸飞机,这篇文章主要介绍智能指针:->和*运算符重载 + 模板技术 实现智能指针(C++)智能指针介绍智能指针原理智能指针实现代码代码运行结果,现在分享给大家,希望可以做个参考。

智能指针介绍

在C++中,我们都知道在堆区new 开辟的内存,必须通过delete 进行内存释放,不然会形成内存泄漏。有时候我们使用了new 后在 写了很多代码,忘记delete 也是很正常的。那么我们可以使用智能指针来避免这种情况,当new内存的使用将放到智能指针内,就可以不用考虑释放问题了。智能指针会帮助我们实现在堆区new的内存的释放

智能指针原理

我们的智能指针类,肯定要包含一个 原始的指针,智能指针 在栈上开辟,那么智能指针一定会被释放掉,一定会走智能指针的析构函数,所有我将 真正在堆上new的内存在 智能指针的析构函数进行释放!

我们将智能指针包裹普通指针后,但是我们还想和原来使用普通指针一样使用-> 和 * 那么肯定要重载运算符,将原始指针进行返回

代码不是很多长,主要就是->、* 运算符的重载 和 模板技术的应用。下面请看代码:

智能指针实现代码

复制代码
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <string> using namespace std; //Person类测试 智能指针 class Person { public: Person(int age,string name) { cout << "Person(int age,string name)" << endl; m_Age = age; m_Name = name; } ~Person() { cout << "~Person()" << endl; } //显示人物信息 void showInfo() { cout << "name = " << m_Name << ", age = " << m_Age << endl; } private: int m_Age; string m_Name; }; //模板 + 指针运算符重载 构成智能指针 template<class classType> class SmartPointer { public: SmartPointer(classType* pointer) { cout << "SmartPointer(classType* pointer)" << endl; this->pointer = pointer; } ~SmartPointer() { cout << "~SmartPointer()" << endl; if (this->pointer != NULL) { delete this->pointer; } } //重载 -> 指针运算符 classType* operator->() { return this->pointer; } //重载 * 解引用运算符 classType& operator*() { return *(this->pointer); } private: classType* pointer; }; int main05(int argc, char *argv[]) { /* 智能指针 只能在栈上建立,这样智能指针一定可以被释放, 那么普通指针就 可以不用管释放的问题,统一由智能指针帮忙释放 实质上用智能指针 将普通指针包起来。 */ SmartPointer<Person> p = SmartPointer<Person>(new Person(18, "Laymond")); p->showInfo(); (*p).showInfo(); return EXIT_SUCCESS; }

代码运行结果

看到没有,智能指针 自动帮忙进行释放,而且使用方式和原来普通指针没有区别哟


最后

以上就是勤奋纸飞机最近收集整理的关于智能指针:->和*运算符重载 + 模板技术 实现智能指针(C++)智能指针介绍智能指针原理智能指针实现代码代码运行结果的全部内容,更多相关智能指针:->和*运算符重载内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(115)

评论列表共有 0 条评论

立即
投稿
返回
顶部