In C + +, programmers can manipulate memory directly, adding a lot of flexibility to programming. But flexibility comes at a cost, and programmers have to be responsible for releasing the memory they're applying for, or there's a memory leak. Smart pointers exist to solve this problem. It has no essential difference from other pointers, and the main purpose is to avoid the problem of hanging pointers and memory leaks. Here, I use the object's app count to do a smart pointer, and when an object has a reference, it does not perform a free memory operation, and when the reference count is 0 o'clock, the memory-free operation is performed and the pointer is reset to NULL.
The code is as follows:
#include <iostream>#include<malloc.h>/*desc:a Smart Pointer to Automatic alloc and dellocat memories. Author:justinzhang ([email protected]). time:2015- 1-22 09:44:24*/Template<classT>classSmartptr { 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 are 0, this pointer would 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;};intMain () {int* p =New int[2]; Smartptr<int>Intsmart (P); Smartptr<int> Copysmart (Intsmart);//copy constructor would be called.smartptr<int> Operatorsmart = Intsmart;//Here the copy consturctor is called, not the assignment operator.Operatorsmart = Intsmart;//Here the assignment operator'll be called. return 0;}
The results of the operation are as follows:
C + + smart pointer smart pointer