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; }
原文地址:http://blog.csdn.net/u011608357/article/details/38281849