在C++中,程序員可以直接操作內存,給編程增加了不少的靈活性。但是靈活性是有代價的,程序員必須負責自己負責釋放自己申請的內存,否則就會出現內存泄露。智能指針就是為了解決這個問題而存在的。它和其他指針沒有本質的區別,主要的目的就是為了避免懸掛指針、內存泄露的問題。在這里,我使用對象的應用計數做了一個smart pointer,當一個對象還有引用的時候,就不執行釋放內存的操作,當引用計數為0時,就執行內存釋放操作,並且將指針重置為NULL。
代碼如下:
#include <iostream> #include <malloc.h> /* desc: A smart pointer to automatic alloc and dellocat memories. author: justinzhang(uestczhangchao@gmail.com). time: 2015-1-22 09:44:24 */ template <class T> class smartPtr { public: smartPtr() { ptr = NULL; refCnt = (unsigned *) malloc(sizeof(unsigned)); } smartPtr( T * pt) { this->ptr = pt; refCnt = (unsigned *) malloc(sizeof(unsigned)); std::cout << "Enter constructor, refCnt is "<< *refCnt << std::endl; *refCnt = 1; std::cout << "Leave constructor, refCnt is " << *refCnt << std::endl; } smartPtr(smartPtr<T> ©) { ptr = copy.ptr; refCnt = copy.refCnt; std::cout << "Enter copy constructor, refCnt is " << *refCnt << std::endl; ++*refCnt; std::cout << "Leave copy constructor, refCnt is "<< *refCnt << std::endl; } smartPtr<T> & operator=(smartPtr<T> ©) { std::cout << "Enter operator=, refCnt is "<< *copy.refCnt << std::endl; if(this != ©) { ptr = copy.ptr; refCnt = copy.refCnt; ++*refCnt; } std::cout << "Leave operator=, refCnt is " << *refCnt << std::endl; return *this; } ~smartPtr() { std::cout << "Enter destructor, refCnt is " << *refCnt << std::endl; --*refCnt; if(*refCnt == 0 ) { std::cout << "In destructor, refCnt is 0 , this pointer will be freed." << std::endl; if( NULL != ptr ) { delete ptr; ptr = NULL; } if(NULL != refCnt ) { free(refCnt); refCnt = NULL; } } else { std::cout << "Leave destructor, refCnt is " << *refCnt << std::endl; } } T getValue() { return *ptr; } protected: T * ptr; unsigned *refCnt; }; int main() { int * p = new int[2]; smartPtr<int > intSmart(p) ; smartPtr<int> copySmart(intSmart); // copy constructor will be called. smartPtr<int> operatorSmart = intSmart ; // Here the copy consturctor will be called, not the assignment operator. operatorSmart = intSmart; // Here the assignment operator will be called. return 0; }
運行結果如下: