智能指针什么时候释放?什么时候引用计数为0

智能指针内部有一个计数器,当赋值给别的智能指针或者函数传参拷贝到另一个shared_ptr,计数器就会加1,当函数执行完毕,智能指针对象 就被析构了,此时计数器就会减一,知道计数器变为0 ,说明没人在用这个对象了,就执行delete把它释放掉。
#include <iostream>
#include <memory>
using namespace std;
class Person
{
public:
	Person(int age,int height)
	{
		this->m_Age = age;
		m_Height = new int(height);
		//this->m_Age
		cout<<"执行有参构造函数"<<endl;
	}
	~Person()
	{	
		if(m_Height!=NULL)
		{
			delete m_Height;
			m_Height = NULL;
		}
		cout<<"执行析构函数"<<endl;
	}
	int m_Age;
	int *m_Height;
	
};
void test(shared_ptr<Person> p1)
{	
	
	shared_ptr<Person> p2(p1);
	cout<<"p2.use_count() ====="<<p2.use_count()<<endl;
	cout<<"p11.use_count() ====="<<p1.use_count()<<endl;
	cout<<"p1 age ==="<<p1->m_Age<<"heihtt==="<<*p1->m_Height<<endl;
	cout<<"p1.get()->m_Age ==="<<p1.get()->m_Age<<"heihtt==="<<*(p1.get()->m_Height)<<endl;
	cout<<"p2 age ==="<<p2->m_Age<<"heihtt==="<<*p2->m_Height<<endl;
	

}
int main()
{	
	shared_ptr<Person> p1(new Person(20,160));
	test(p1);
	cout<<"p1.use_count() ====="<<p1.use_count()<<endl;
	return 0;
}

执行有参构造函数
p2.use_count() =====3
p11.use_count() =====3
p1 age ===20heihtt===160
p1.get()->m_Age ===20heihtt===160
p2 age ===20heihtt===160
p1.use_count() =====1
执行析构函数

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值