码迷,mamicode.com
首页 > 其他好文 > 详细

智能指针

时间:2014-07-30 01:02:42      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:智能指针   c++   内存泄露   

       C++中智能指针可以防止出现野指针、内存泄露等情况,智能指针的类中包含4个函数:构造函数、拷贝构造函数、重载复制操作符、析构函数。构造函数需要对引用计数和指针进行初始化,引用计数初始化为1,拷贝构造函数完成对象之间的拷贝,要注意引用计数的变化和判断两个指针是否指向相同的内存。重载复制操作符,需要判断的情况是左值代表的指针如果引用计数减为0,要释放相应的内存,避免发生内存泄露。析构函数中先判断引用计数是否为0,引用计数为0时再释放相应的内存。

# include <iostream>
# include <cstdlib>
using namespace std;

template <typename T>
class smartptr
{
public:
	smartptr(T *p):use(1),ptr(p){;}
	smartptr(const smartptr<T> &p);
	smartptr<T> & operator =( smartptr <T>& p);
	~smartptr()
	{
		if(--(*this).use==0)
		{
			delete ptr;
			cout<<"deconstructor"<<endl;
		}
		ptr=NULL;
	}
private:
	int use;
	T *ptr;
};

template<class T>
smartptr<T>::smartptr(const smartptr<T> &p)
{
	this->ptr=p.ptr;
	this->use=p.use;
	this->use++;
}

template<class T>
smartptr<T> & smartptr<T>::operator =( smartptr <T>& p)
{
	if(this!=&p)
	{
	if(--(*this).use==0)
		delete ptr;
	this->ptr=p.ptr;
	this->use=p.use;
	this->use++;
	}
return *this;
}

int main()
{
int *t=new int(3);
int *p=new int(4);
smartptr <int > p1(t);
smartptr<int> p2(p1);
smartptr<int> p3=p1;
smartptr<int> p4(p);
p4=p1;
system("pause");
return 0;
}



智能指针,布布扣,bubuko.com

智能指针

标签:智能指针   c++   内存泄露   

原文地址:http://blog.csdn.net/u011608357/article/details/38281849

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!