智能指针分析
2021/12/1 6:08:41
本文主要是介绍智能指针分析,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
智能指针为了解决内存泄漏的问题而诞生
内存泄漏:
(1)动态申请堆空间,用完后不归还
(2)C++语言中没有垃圾回收的机制
(3)指针无法控制所指堆空间的生命周期
编程实验:内存实验
#include <iostream> #include <string> using namespace std; class Test { int i; public: Test(int i) { this->i = i; } int value() { return i; } ~Test() { } }; int main() { for(int i = 0; i < 5; i++) { Test* p = new Test(i); //内训泄漏,用完不归还 cout << p->value() << endl; } return 0; }
深度思考:
我们需要什么?
(1)需要一个特殊的指针
(2)指针生命周期结束时主动释放堆空间
(3)一片堆空间最多只能由一个指针表示
(4)杜绝指针运算和指针比较
解决方案
(1)重载指针特征操作符(->和)*
(2)只能通过类的成员函数重载
(3)重载函数不能使用参数
(4)只能定义一个重载函数
编程实验:智能指针
#include <iostream> #include <string> using namespace std; class Test { int i; public: Test(int i) { this->i = i; cout << "Test" << endl; } int value() { return i; } ~Test() { cout << "~Test()" << endl; } }; class Pointer { Test* mp; public: Pointer(Test* p = NULL) { mp = p; cout << "Pointer" << endl; } Test* operator -> () { return mp; } Test& operator * () { return *mp; } ~Pointer() { delete mp; cout << "~Pointer()" << endl; } }; int main() { for(int i = 0; i < 5; i++) { Pointer p = new Test(i); cout << p->value() << endl; } return 0; }
#include <iostream> #include <string> using namespace std; class Test { int i; public: Test(int i) { this->i = i; cout << "Test" << endl; } int value() { return i; } ~Test() { cout << "~Test()" << endl; } }; class Pointer { Test* mp; public: Pointer(Test* p = NULL) { mp = p; cout << "Pointer" << endl; } Pointer(const Pointer& obj) { mp = obj.mp; const_cast<Pointer&>(obj).mp = NULL; cout << "Pointer(const Pointer& obj)" << endl; } Pointer& operator=(const Pointer& obj) { if(this != &obj) { delete mp; mp = obj.mp; const_cast<Pointer&>(obj).mp = NULL; cout << "Pointer& operator=" << endl; } return *this; } bool isNULL() { return (mp == NULL); } Test* operator -> () { return mp; } Test& operator * () { return *mp; } ~Pointer() { delete mp; cout << "~Pointer()" << endl; } }; int main() { Pointer p1 = new Test(0); cout << p1->value() << endl; Pointer p2 = p1; cout << p1.isNULL() << endl; cout << p2->value() << endl; return 0; }
智能指针使用军规:
只能用来指向堆空间中的对象或者变量
小结:
(1)重载智能指针特征符能够使用对象代替指针
(2)智能指针只能用于指向堆空间中的内存
这篇关于智能指针分析的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-09-28AI给的和自己写的Python代码,都无法改变输入框的内容,替换也不行
- 2024-09-27Sentinel配置限流资料:新手入门教程
- 2024-09-27Sentinel配置限流资料详解
- 2024-09-27Sentinel限流资料:新手入门教程
- 2024-09-26Sentinel限流资料入门详解
- 2024-09-26Springboot框架资料:初学者入门教程
- 2024-09-26Springboot框架资料详解:新手入门教程
- 2024-09-26Springboot企业级开发资料:新手入门指南
- 2024-09-26SpringBoot企业级开发资料新手指南
- 2024-09-26Springboot微服务资料入门教程