内存泄漏(臭名昭著的 Bug)ios
- 动态申请堆空间,用完后不归还
- C++ 语言中没有垃圾回收的机制
- 指针没法控制所指堆空间的生命周期
#include <iostream> #include <string> using namespace std; class Test { private: int i; public: Test(int i) { this->i = i; } int value() { return i; } ~Test() { } }; int main() { for(int i=0; i<5; i++) // 若是是 5000000 次呢? { Test* p = new Test(i); cout << p->value() << endl; } return 0; }
输出: 0 1 2 3 4
咱们须要什么编程
- 须要一个特殊的指针
- 指针生命周期结束时主动释放堆空间
- 一块堆空间最多只能由一个指针表示(避免内存屡次释放)
- 杜绝指针运算和指针比较(避免越界形成野指针)
解决方案函数
- 重载指针特征操做符( -> 和 *)
- 只能经过类的成员函数重载
- 重载函数不能使用参数(只能定义一个重载函数)
#include <iostream> #include <string> using namespace std; class Test { private: int i; public: Test(int i) { cout << "Test(int i)" << endl; this->i = i; } int value() { return i; } ~Test() { cout << "~Test()" << endl; } }; class Poniter { private: Test* m_pointer; public: Poniter(Test* p = NULL) { m_pointer = p; } Poniter(const Poniter& obj) { m_pointer = obj.m_pointer; // 全部权转接 const_cast<Poniter&>(obj).m_pointer = NULL; } Poniter& operator = (const Poniter& obj) { if( this != &obj ) { delete m_pointer; // 全部权转接 m_pointer = obj.m_pointer; const_cast<Poniter&>(obj).m_pointer = NULL; } return *this; } Test* operator -> () { return m_pointer; } Test& operator * () { return *m_pointer; } bool isNull() { return (m_pointer == NULL); } ~Poniter() { delete m_pointer; } }; int main() { Poniter p1 = new Test(0); cout << p1->value() << endl; Poniter p2 = p1; cout << p1.isNull() << endl; cout << p2->value() << endl; return 0; }
输出: Test(int i) 0 1 0 ~Test()
- 智能指针的使用军规: 只能用来指向堆空间中的对象或者变量
- 指针特征操做符 ( -> 和 * ) 能够被重载
- 重载指针特征符可以使用对象代替指针
- 智能指针只能用于指向堆空间中的内存
- 智能指针的意义在于最大程序的避免内存问题
以上内容参考狄泰软件学院系列课程,请你们保护原创this