您的位置:首页 > 其它

智能指针

2016-01-10 12:30 337 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: