C++ | shared_ptr
shared_ptr允许多个指针指向同一个对象,shared_ptr的引用计数为指向该对象shared_ptr的数量,当引用计数为0时自动释放该对象。
智能指针是对指针的封装。
智能指针是模版。
使用智能指针需要包含头文件
#include <memory>
shared_ptr<string> p1; // shared_ptr,可以指向string shared_ptr<vector<int>>p2; // shared_ptr,可以指向int的vector shared_ptr<int> p3 (new int(100));
shared_ptr的一些操作
shared_ptr<T> p | 空只能指针,可以指向类型为T的对象 |
p | if(p),若p指向一个对象,表达式为true |
*p | 解引用 |
p->attr | 等价于(*p).attr |
p->get() | 返回p中保存的指针 |
swap(p,q) | 交换p和q中的指针 |
p.swap(q) | 交换p和q中的指针 |
make_shared<T>(args) | 返回一个shared_ptr对象,用args初始化 |
shared_ptr<T>p(q) | p是q的拷贝 |
p=q | p的引用计数会递减,q的引用计数递增 |
p.unique() | 若p.use_count()为1,返回true,否则false |
p.use_count() | 返回引用计数 |
shared_ptr<int> p1 (new int(100)); cout << "p1.use_count(): " << p1.use_count() << endl; cout << "*p1: " << *p1 << endl; shared_ptr<int> p2 = p1; cout << "p2.use_count(): " << p2.use_count() << endl; cout << "p1.use_count(): " << p1.use_count() << endl; cout << "*p2: " << *p2 << endl; shared_ptr<int> p3 = make_shared<int>(200); cout << "p3.use_count(): " << p3.use_count() << endl; cout << "*p3: " << *p3 << endl; /* 输出为 p1.use_count(): 1 *p1: 100 p2.use_count(): 2 p1.use_count(): 2 *p2: 100 p3.use_count(): 1 *p3: 200 */#c++##智能指针#