Header File: Cmfc2Dlg.h template <class T>class RefCount { protected: int refVal; T* p; public: RefCount(){ refVal=0; p=(T*)this;} void AddRef() { refVal++; } void ReleaseRef() { refVal--; if(refVal == 0) delete [] this; } T* operator->(void) { return p; } }; template <class T> class gcPtr { T* ptr; char c; public: gcPtr() { c='0'; // called when variable declare // as gcPtr<foo> a; } gcPtr(T* ptrIn) { ptr=ptrIn; // called when variable declared // as gcPtr<foo> a=new foo; ptr->AddRef(); c='1'; } // assuming we have variable gcPtr<foo> x operator T*(void) { return ptr; } //for x[] T& operator*(void) { return *ptr; } // for *x type operations T* operator->(void){ return ptr; } // for x-> type operations gcPtr& operator=(gcPtr<T> &pIn) // for x=y where y is also gcPtr<foo> object { return operator=((T *) pIn); } gcPtr& operator=(T* pIn) { if(c=='1') // called by gcPtr& operator=(gcPtr<T>&pIn) in case of { // assignment // Decrease refcount for left hand side operand ptr->ReleaseRef(); // of ‘=’ operator ptr = pIn; pIn->AddRef(); // Increase reference count for the Right Hand // operand of ‘=’ operator return *this; } else // if c=0 i.e variable was not allocated memory when // it was declared { // like gcPtr<foo> x. in this case we //allocate memory using new // operator, this will be called ptr=pIn; ptr->AddRef(); return *this } } ~gcPtr(void) { ptr->ReleaseRef(); } // Decrement the refcount }; class Cmfc2Dlg : public CDialog,RefCount<Cmfc2Dlg> { public: void Take_Screenshot(); //other function declarations.. }
//Source file: Cmfc2Dlg.cpp void Cmfc2Dlg :: OnBnClickedOK() { while(1) { //Am running Take_Screenshot function forever: gcPtr <cmfc2Dlg> obj = new Cmfc2Dlg(); obj->Take_Screenshot(); } }
shared_ptr
InterlockedIncrement
InterlockedDecrement
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)