C++:初识智能指针

初识智能指针:

8种:
auto_ptr(VC版)
auto_ptr(VS版或Linux版,符合标准C++)
Boost   (Boost程序库完全开发指南.pdf):
scoped_ptr、scoped_array、shared_ptr、shared_array、weak_ptr、intrusive_ptr


智能指针:拿对象模拟指针,还负责内存的自动释放;

     拥有权管理和转移

<span style="font-size:18px;">#include <iostream>
#include <memory>
#include <string>
using namespace std;

int main()
{
	int *p = new int(10);
	auto_ptr<int> pa(p);               //delete p;
	cout<<*pa<<endl;                   //*p
	
	string *ps = new string("hello");
	auto_ptr<string> pa1(ps);         //delete ps;
	cout<<pa1->size()<<endl;           //p->
	return 0;
}</span>

/

<span style="font-size:18px;">template <class _Ty>
class auto_ptr
{
public:
	auto_ptr(_Ty *_P=0):_Owns(_P!=0),_Ptr(_P)
	{}
	~auto_ptr()           //1.对象析构的时候释放指针所指的空间,即表现出智能指针的智能部分
	{
		if(_Owns)
			delete _Ptr;
	}
public:
	_Ty& operator*()const    //2.重载*p 和 p-> ,即表现出智能指针的指针部分
	{
		return *_Ptr;
	}
	_Ty* operator->()const
	{
		return _Ptr;
	}
private:
	bool _Owns;
	_Ty *_Ptr;
};

class Test
{
public:
	void fun()const
	{
		cout<<"This is Test fun()"<<endl;
	}
};

int main()
{
	int *p = new int(10);
	auto_ptr<int> pa(p);	
	cout<<*pa<<endl;

	Test *pt = new Test;
	auto_ptr<Test> pa1(pt);
	pal->fun();

	return 0;
}</span>

智能指针的核心问题在于拥有权管理和转移

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值