为了解决C++内存泄漏的问题,C++11引入了智能指针(Smart Pointer)
平时在C++代码中当new一片内存,在用delete即可使用,释放内存,当代码量过大时,难免有内存泄露。为了解决这个问题,C++11新加了智能指针,简单的来说就是以后new一个对象,把它指向智能指针shared_ptr即可不用写delete了。
-
简单的实操
#include "iostream"
#include <memory>
using namespace std;
int main()
{
int* p0 = new int(123); //如果不用delte则此线程结束,则new的内存未被自动释放。
//类似的如文件被打开,如用了fopen()未用fclose()则会浪费资源。
delete p0;
//智能指针---可自动的释放内存,不用担心用了new,没用delete导致内存泄露
int* p = new int(123);
shared_ptr<int> pInt0 = p;
shared_ptr<int> pInt1 = make_shared<int>(123); //指向一个值为123的int的pInt指针
//make_shared<int>(123)相当于new int(123)
}
-
shared_ptr的原理
- 在构造的时候传入一个new出来的对象,count +1
- 重载操作符 * -> = 之类的来进行引用计数+1
- 在析构函数对count -1,利用局部变量的析构
- 当析构函数为0则delete传入的对象
namespace MyPtr { class A { public: int a; int b; }; template <typename T> class shared_ptr { // 构造函数来new public: shared_ptr(T ptr) { m_ptr = ptr; count = 1; } // 重构 -> 并使用一次就增加计数 T operator->() { count++; return m_ptr; } // 析构函数== 0才delete ~shared_ptr() { count--; printf("[%d] over use count == %d\n", &m_ptr, count); if (count == 0) { delete m_ptr; } }; // 模板类来保证可定义各个类型的shard_ptr // 多线程安全 // others int use_count() { printf("[%d] use count == %d\n", &m_ptr, count); return count; } int test; private: int count; T m_ptr; /* 类模板不能重载 = shared_ptr<T>& operator=(const shared_ptr<T>& tmp) { count = tmp->count; m_ptr = tmp->m_ptr; count++; printf("36 use count == %d\n", count); return m_ptr; }*/ };
调用示例:
int main() { { MyPtr::shared_ptr<MyPtr::A*> p1(new MyPtr::A); p1.use_count(); // 1 p1->a; p1.use_count(); // 2 } 出了作用域,调用p1的析构函数use_count()-1,变为1; }
- 多线程安全,所以最好在计数操作的时候加锁