C++11 shared_ptr智能指针

 

#include<iostream>
using namespace std;
#include<memory>

class test {
public:
	test(int no) {
		this->no = no;
		cout << "调用构造函数: " << no << endl;
	}
	~test() {
		cout << "调用析构函数: " << no << endl;
	}
private:
	int no;
};

 

 

构造方式一: 

	shared_ptr<test>sp;
	shared_ptr<test>sp2(new test(1));
	
	//use_count :当前管控同一个对象的智能指针对象
	cout<<"sp.use_count:" << sp.use_count() << endl;//0
	cout<<"sp2.use_count:" << sp2.use_count() << endl;//1

	sp = sp2;
	cout << "----sp = sp2----" << endl;
	cout << "sp.use_count:" << sp.use_count() << endl;//2
	cout << "sp2.use_count:" << sp2.use_count() << endl;//2

	shared_ptr<test>sp3(sp);
	cout << "---shared_ptr<test>sp3(sp)---" << endl;
	cout << "sp.use_count:" << sp.use_count() << endl;//3
	cout << "sp2.use_count:" << sp2.use_count() << endl;//3
	cout << "sp3.use_count:" << sp3.use_count() << endl;//3
	//sp.use_count() == sp2.use_count() == sp3.use_count()

	system("pause");

结果: 

构造方式二: C++17之后支持

    //数组对象管理
	shared_ptr<test[]>arr(new test[5]{ 11, 22, 33, 44, 55 });

 结果:

 构造方式三:

//仿函数
class DestructTest {
public:
	void operator()(test* t) {
		cout << "调用DestructTest... " << endl;
		delete t;
	}
};
shared_ptr<test>sp(new test(666), DestructTest());

 

 

 使用make_shared初始化对象,分配内存效率更高

	//使用make_shared初始化对象,分配内存效率更高
	// make_shared<类型>(参数)
	shared_ptr<string>s = make_shared<string>("ABC");
	shared_ptr<string>s2;
	s2 = make_shared<string>("abc");

 主动释放对象:

	//主动释放对象
	shared_ptr<string>s = make_shared<string>("ABC");
	s = NULL;
	//或
	// s = nullptr;

重置:

 交换:

使用陷阱:shared_ptr作为被管控对象的成员时,小心因循环引用造成资源无法释放. (weak_ptr)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值