Smart pointers initial understanding - to achieve their own

Smart pointers (managed object pointer)

目的:new出来的对象,需要程序员自己释放堆上的空间,智能指针就是把堆上的空间同栈一起释放
重载:* -> ,让智能指针像普通指针一样使用

Code analysis more straightforward

#include <iostream>
using namespace std;

class Person
{
public:
	Person(int age)
	{
		cout<<"构造调用"<<endl;
		this->m_Age=age;
	}

	void showAge()
	{
		cout<<"年龄为:"<<m_Age<<endl;
	}
	~Person()
	{
		cout<<"析构调用"<<endl;
	}
private:
	int m_Age;
};
//智能指针类
class smartPointer
{
public:
	smartPointer(Person *person)
	{
		this->m_person=person;
	}
	//重载->,像Person *p 的p一样去使用对象
	Person * operator->()
	{
		return this->m_person;
	}
	//重载*
	Person& operator*()
	{
		return *this->m_person;
	}

	//智能指针析构时,带走Person
	~smartPointer()
	{
		if(m_person !=NULL)
		{
			delete m_person;
			m_person=NULL;
		}
	}
private:
	Person * m_person;
};

void test01()
{
	smartPointer sp(new Person(20));//用智能指针类将对象指针包装起来,实现new开辟堆的指针同栈一块释放

	sp->showAge();
	(*sp).showAge();
}



int main()
{
	 test01();
	return 0;
}
Published 38 original articles · won praise 13 · views 4341

Guess you like

Origin blog.csdn.net/YanWenCheng_/article/details/103927059