c++智能指针(auto_ptr)

auto_ptr的简单实现

#include<iostream>
using namespace std;

/*

	智能指针    boos库里的智能指针


	c++11以前ato_ptr
	后   unique_ptr shared_ptr weak_ptr
*/
//auto_ptr智能指针的实现
template<typename T>
class Smart_ptr
{
public:
	Smart_ptr(T*ptr)
	{


	}
	Smart_ptr(const Smart_ptr<T>& rhs):mptr(rhs.mptr)//拷贝构造函数
	{
		rhs.release();//rhs是一个常对象
	}
	Smart_ptr<T>& operator=(const Smart_ptr<T>&rhs)
	{
		if(this!=&rhs)//自赋值判断
		{
			delete mptr;
			mptr=rhs.mptr;
			rhs.release();
		}
		return *this;
	}

	~Smart_ptr()
	{
		delete mptr;
		mptr=NULL;
	}
	//实现对象解引用  重载函数
T&	operator*()//*单目运算符   里面有this指针做唯一操作数
{
	return *mptr;
}
//->指向运算符的重载    单目运算符
T *operator->()
{
	return mptr;
}

private:
	void release()const//改变旧智能指针的指向rhs是常对象
	{
		((Smart_ptr<T>*)this)->mptr=NULL;//强转
	}
	T* mptr;

};
/*
	int *p=new int;  *p=20;
	class Test
	{
	public:
	void Show();
	}
	Test* ptest =new Test();
	ptest->Show();  指针不仅要解引用 还要能调用函数     智能指针要把它当做一个指针 所以要有解引用 和指向操作   ----》运算符重载
*/
class Test
{
public:
	void Show()
	
	{
		cout<<"Test::Show()"<<endl;
	}
};

//auto_ptr被摒弃的原因  管理权是唯一的  释放权也唯一
int main()
{
	Smart_ptr<int>sp1(new int);
	Smart_ptr<int>sp2(sp1);
	*sp1=20;//访问保留区
}



/*
int main()
{
	Smart_ptr<int>sp1(new int);
	//Smart_ptr<int>sp2(sp1);//发生浅拷贝  sp1 拷贝sp2
	Smart_ptr<int>sp2(sp1);
    Smart_ptr<int>sp3(new int);
	sp3=sp2;//赋值运算符的重载函数,指向同一块地址,要实现这个该函数 
	*sp3=20;
	Smart_ptr<Test>sp4(new Test());
	sp4->Show;    //sp4.operator->()   ----->Test*  ---->Show()
	return 0;
}

*/






















//void func(int *ptr)
//{
//	auto_ptr<int>p(new int);
//	//int *p=new int;
//	if(ptr==NULL)
//	
//	{
//		throw exception("ptr is null");
//	}
//	*p=*ptr;
//	//delete p'
//}
//int main()
//{
//	func(NULL);
//	return 0;
//}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值