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

智能指针内部有一个计数器,当赋值给别的智能指针或者函数传参拷贝到另一个shared_ptr,计数器就会加1,当函数执行完毕,智能指针对象 就被析构了,此时计数器就会减一,知道计数器变为0 ,说明没人在用这个对象了,就执行delete把它释放掉。
#include 
#include 
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
执行析构函数

你可能感兴趣的:(C++)