使用引用计数的方法管理动态内存。
// 空的share_ptr
shared_ptr<T> sp;
// 用 make_shared 方法构造
shared_ptr<T> sp(make_shared<T>(args));
// 用 shared_ptr 构造
shared_ptr<T> sp1 = sp2;
// 用内置指针构造。此构造函数是 explicit 的
shared_ptr<T> sp(q);
// 释放时用可调用对象d代替delete
shared_ptr<T, d> sp(q, d);
// 赋值。递减sp1的引用计数(变为0则释放),递增sp2的引用计数
sp1 = sp2;
// 返回内置指针
sp.get();
// 交换保存对象
swap(sp1, sp2);
sp1.swap(sp2);
// 引用计数是否为1
sp.unique();
// 返回引用计数。慢,用于调试
sp.use_count();
// reset系列方法放弃管理原对象(引用计数递减)
sp.reset();
// sp接管内置指针
sp.reset(q);
// 用可调用对象d代替delete
sp.reset(q, d);
shared_ptr在构造时捕获了管理对象的析构行为,所以会发生下列情况。
例1:
#include <iostream>
#include <memory>
using namespace std;
class CBase
{
public:
CBase() {};
// 注意并没有虚析构
~CBase() {
cout << "~CBase()" << endl;
};
};
class CDerive : public CBase
{
public:
CDerive() {};
~CDerive() {
cout << "~CDerive()" << endl;
};
};
int main(int argc, char* argv[])
{
shared_ptr<CBase> sp(new CDerive());
return 0;
}
输出:
~CDerive()
~CBase()
例2:
#include <iostream>
#include <memory>
using namespace std;
class CObj
{
public:
CObj() {};
~CObj() {
cout << "~CObj()" << endl;
};
};
int main(int argc, char* argv[])
{
shared_ptr<void> sp(new CObj());
return 0;
}
输出:
~CObj()
我对于以上行为的理解参考了:https://www.cnblogs.com/Solstice/archive/2013/01/28/2879366.html
一种“弱共享”对象的方法。如果shared_ptr相当于铁丝,那么weak_ptr相当于棉线。
// 空的weak_ptr
weak_ptr<T> w;
// p可以是weak_ptr或shared_ptr
weak_ptr<T> w(p);
w = p;
// 尝试将weak_ptr提升为shared_ptr(线程安全)
w.lock();
// 将w置空
w.reset();
// 是否过期(w.use_count()是否为0)
w.expired();
// 与w共享对象的share_ptr的数量
w.use_count();
原文:https://www.cnblogs.com/bwzdxl/p/12770395.html