c++智能指针主要是解决内存管理的问题,比如我们new delete需要成对的使用,否则会发生内存泄漏,智能指针很大程度上可以解决这个问题,智能指针是一个类,当超出了类的作用类时,类会自动调用析构函数进行释放;
首先介绍关于类什么时候调用析构函数;
- 类的生命周期结束的时候
- 类的生命周期结束的标志就是当类的对象不再后面存在的时候,show the code:
-
#include <iostream> #include <queue> #include <stdlib.h> #include<memory> #include<string> #define LL long long using namespace std; class A { public: A() { cout << "constructing A" << endl; } void print() { cout << a << endl; } ~A() { cout << "destructing A" << endl; } private: int a; }; int main() { A a; a.print(); return 0; }
- 主动调用delete函数
- 直接调用delete函数
- 对象i是对象o的成员,o的析构函数被调用时,对象i的析构函数也被调用。