背景
曾经有个面试官问我所了解的智能指针,今天来总结一下^_^
C++ 11中的智能指针
C++ primer中提到4种指针
- shared_ptr
- unique_ptr(auto_ptr)
- weak_ptr
auto_ptr是C++ 98标准中的自动指针,unique_ptr是C++ 11标准中对应的升级版,但auto_ptr仍然是标准库的一部分,auto_ptr具有unique_ptr的部分特性,但不是全部。
还有boost中的提到了6种智能指针
- scoped_ptr
- scoped_array
- shared_ptr
- shared_array
- weak_ptr
- intrusive_ptr
其中的shared_ptr和weak_ptr已经被收录到C++ 11标准中了。
概述各个指针的功能
shared_ptr:引用计数智能指针
unique_ptr(auto_ptr):所有权转移智能指针
weak_ptr:shared_ptr的助手,peek一下shared_ptr管理的资源
scoped_ptr:所有权不转让智能指针
scoped_array:类似scoped_ptr,指向动态数组的智能指针
shared_array:类似shared_array,指向动态数组的智能指针
intrusive_ptr:侵入式的引用计数型指针
其详细用法请查看C++ primer(第五版)的第12章动态内存
同时查看boost程序库完全开发指南的第3章内存管理