智能指针

本文介绍了一种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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值