Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version

Automatic Garbage Collection in C++ using Smart pointers

, 18 May 2003
This article explains how to prevent your programs from memory leaks, by incorporating Garbage Collector in your class.
gc_demo.zip
gcdemo.exe
gc_src.zip
DIALOG1.DSW
dialog1.dsp
/*********************************************************************/
//         Written by: Muhammad Shoaib Khan
//			email:     sbk_one@yahoo.com
//        Garbage collection classes are free to use for any purpose
/**********************************************************************/

#ifndef _GC_PTR_

#define _GC_PTR_ 
template <class T> class gcPtr 
{
	T* ptr;
	char c;
public:
	gcPtr()
	{
		c='0';
	}
	gcPtr(T* ptrIn)
	{
		ptr=ptrIn;
		ptr->AddRef();
		c='1';
	}
	
	operator T*(void)  { return ptr;  }
	T& operator*(void) { return *ptr; }
	T* operator->(void){ return ptr;  }
	gcPtr& operator=(gcPtr<T> &pIn)
	{return operator=((T *) pIn);}
    gcPtr& operator=(T* pIn) 
	{
		if(c=='1')
		{
			
			ptr->ReleaseRef();
			ptr = pIn;
			pIn->AddRef();
			return *this;
			
		}
		else
		{
			ptr=pIn;		
			ptr->AddRef();
			return *this;
			
		}
	}
	~gcPtr(void) { ptr->ReleaseRef(); }
};
#endif

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

abc876
Web Developer
Pakistan Pakistan
No Biography provided

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.141216.1 | Last Updated 19 May 2003
Article Copyright 2003 by abc876
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid