【C++】模拟实现auto_ptr

  看了《Effctive C++》,里面提到用对象去管理资源,可以有效防止内存泄漏.

  结合auto_ptr特性,稍微思考了一下,实现了一个简单的auto_ptr

  (因为代码量小,就不分文件了)

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
template<typename T>
class AutoPtr{
public:
	//构造函数
	AutoPtr(T *ptr = NULL)
		:_ptr(ptr){}
	//拷贝构造函数
	AutoPtr(AutoPtr & p)
		:_ptr(p._ptr){
		p._ptr = NULL;
	}
	//赋值运算符重载
	AutoPtr &operator=(AutoPtr &p){
		//判断自我赋值
		if (_ptr != p._ptr){
			//
			if (_ptr != NULL){
				delete _ptr;
				_ptr = NULL;
			}
			_ptr = p._ptr;
			p._ptr = NULL;
		}
		return *this;
	}
	//对*重载
	T& operator*(){
		return *_ptr;
	}
	//对->重载
	T* operator->(){
		return _ptr;
	}
	//析构函数
	~AutoPtr(){
		if (_ptr != NULL){
			delete _ptr;
			_ptr = NULL;
		}
	}
private:
	T *_ptr;
};
//测试函数
void FunTest(){
	int *p = new int(5);
	AutoPtr<int> ap1(p);
	AutoPtr<int> ap2(ap1);
	AutoPtr<int> ap3;
	ap3 = ap2;
	p = new int(10);
	AutoPtr<int> ap4(p);
	ap4 = ap3;
}
int main(){
	FunTest();
	return 0;
}

  所以这个auto_ptr感觉还有挺坑的,只能有一个对象掌握资源,如果想用多个对象管理同一资源的话....考虑使用share_ptr.

posted @ 2016-11-17 21:06  C/C++专题  阅读(565)  评论(0编辑  收藏  举报