永恒的话题内存泄漏(臭名昭著的 Bug)动态申请堆空间,用完后不归还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;}输出:01234深度的思考我们需要什么需要一个特殊的指针指针生命周期结束时主动释放堆空间一块堆空间最多只能由一个指针表示(避免内存多次释放)杜绝指针运算和指针比较(避免越界造成野指针)智指针分析解决方案重载指针特征操作符( -> 和 )只能通过类的成员函数重载重载函数不能使用参数(只能定义一个重载函数)编程实验: 智能指针#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)010Test()智能指针的使用军规: 只能用来指向堆空间中的对象或者变量 小结指针特征操作符 ( -> 和 * ) 可以被重载重载指针特征符能够使用对象代替指针智能指针只能用于指向堆空间中的内存智能指针的意义在于最大程序的避免内存问题以上内容参考狄泰软件学院系列课程,请大家保护原创