- 智能指针
- unique_ptr
- shared_ptr
- weak_ptr
- ----有空再补充
- 智能指针相比于普通指针,避免了内存泄漏的问题,能够在适当时机自动释放所占堆内存。
- C++11标准库提供了三种智能指针, shared_ptr, weak_ptr, unique_ptr
- 使用需要引入头文件
unique_ptr独占所指堆内存空间,无法与其他指针共享,当该内存的引用计数为0,立刻进行内存回收。
- 简单使用
// https://en.cppreference.com/w/cpp/memory/unique_ptr #include
#include using namespace std; int main() { unique_ptr up1(new string("unique_ptr")); cout << &up1 << " " << *up1 << endl; // out: 0x7ffddfcc9b48 unique_ptr // unique_ptr up2(up1); // compile error unique_ptr up2(new string); *up2 ="unique_ptr"; cout << &up2 << " " << *up2 << endl; // out: 0x7ffddfcc9b50 unique_ptr return 0; }
- shared_ptr允许多个指针指向同一个对象,
// https://en.cppreference.com/w/cpp/memory/shared_ptr #includeweak_ptr#include using namespace std; class A { public: A(int i): n(i) { cout << "A init..." << endl; } ~A() { cout << "A end..." << endl; } private: int n; }; int main() { shared_ptr sp1(new A(1)); cout << sp1 << " " << sp1 << " " << sp1.use_count() << endl; shared_ptr sp2(sp1); cout << sp2 << " " << sp2 << " " << sp2.use_count() << endl; return 0; }
- 为了避免shared_ptr循环引用(即A、B互相引用导致内存泄漏),C++11引入了weak_ptr,它是一种弱引用,指向shared_ptr所管理的对象



