bpkg

C++的智能指针

两盒软妹~` 提交于 2021-01-09 06:46:30
上一篇笔记提到C++的智能指针,本节重点写一下智能指针的应用场景和使用中的坑 智能指针的背景 C++中比较头疼的是内存泄露问题,如果使用new动态申请内存,需要时刻记得delete回收内存,避免发生内存泄露。 对于分支很多的代码来讲,在多个分支进行内存释放很容易产生遗漏,排查代码非常浪费时间。 为了避免这种情况,C++采用智能指针的方式进行内存管理,智能指针本身就是一个类,在类的对象超出作用域范围时,会自动调用析构函数。 auto_ptr的坑 C++11之前,只有auto_ptr,不过auto_ptr存在很多缺点,如: auto_ptr只能唯一引用内存地址,如果使用拷贝构造函数,会造成所属权的转移,导致以前的指针无效,此时如果再使用以前的指针会导致非法访问 如: 1 #include <iostream> 2 #include <memory> 3 4 using namespace std; 5 6 class A 7 { 8 public : 9 A( int num) { _num = num; } 10 ~A() { cout << " distroy A " << endl; } 11 int get () { return _num; } 12 void set ( int num) { _num = num; } 13 void show() { cout << "