智能指针

       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;
}



原文地址:https://www.cnblogs.com/gcczhongduan/p/5118167.html