C++11中的智能指针

理解智能指针

在C++的程序设计中,经常需要在堆空间上进行内存的申请和释放,为了方便,C++11引出了智能指针,更好的管理堆内存,避免一些儿二次释放空间和未释放空间的情况。

这种智能指针是在栈空间存放的。

智能指针功能形同指针,但是本质是一个对象。
有三种智能指针:shared_ptr,unique_ptr,weak_ptr。使用时,需要引用< memory>头文件。

shared_ptr

字如其意,shared_ptr所指向的对象可以有多个指针指向它,这是使用记录引用次数的方式来实现的。当拷贝一次shared_ptr时候,对象的引用次数就增加一次。没析构一次,引用的次数就减少一次。当计数为0时,就释放空间。

基本使用

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

class People
{
public:
	People(string s)
	{
		name=s;
		cout<<name<<" construction"<<endl;
	}
	~People()
	{
		cout<<name<<" destruction"<<endl;
	}
private:
	string name;
	
};
int main()
{
	shared_ptr<People>ptr1(new People("rita"));
	shared_ptr<People>ptr2(ptr1);
	shared_ptr<People>ptr3(make_shared<People>("hero"));
	
	cout<<ptr1.use_count()<<endl;
	cout<<ptr2.use_count()<<endl;
	cout<<ptr3.use_count()<<endl;
	
    return 0;
}

运行结果

rita construction
hero construction
2
2
1
2
2
1
hero destruction
rita destruction

unique_ptr

相对于shared_ptr智能指针,unique_ptr指针在某时刻唯一的指向所指对象。unique_ptr指针的生命周期是从创建到作用域结束。
不允许赋值和拷贝,但是允许move。

weak_ptr

为了配合shared_ptr,用于观测资源的使用情况。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值