Click here to Skip to main content
15,885,875 members
Articles / Programming Languages / C++

A Generational Garbage Collector in C++

Rate me:
Please Sign up or sign in to vote.
2.57/5 (15 votes)
17 Dec 20015 min read 124.1K   2.5K   61  
A Garbage Collector framework that is based upon Generational Copying
// GC.h: interface for the CGarbageCollector class.
//
//////////////////////////////////////////////////////////////////////
#ifndef _GARBAGECOLLECTOR_H
#define _GARBAGECOLLECTOR_H

#include "stdafx.h"
#include "Pointer.h"
#include "Generation.h"

class GC
{
private:
// Array of pointers to pointers that are made on the stack
	static std::vector< void** > _PointersOnStack;
// Holds the size of objects that are made on the stack
	static std::vector< unsigned int > _SizeOfObjects;
// Holds all the generations	
	static std::vector< Generation* > _Generations;
// Holds total bytes allocated on the heap
	static int BytesAllocated;	
// Class would not have any instance.
	GC() { } 
	
	virtual ~GC() { }
	
public:
// Invokes the GC for all generations
	static void Collect();
// Invokes the GC only upto and including the generation specified
	static void Collect( Generation*& pGeneration );
// Call this to allocate memory from the garbage collector
	static void* operator new( size_t, void** pStackPtr );
// Gets maximum number of generations that have been made
	static int GetMaxGeneration();
// Gets the total memory (bytes) that has been allocated on the heap
	static int GetTotalBytesAllocated() { return BytesAllocated; }
// Returns the total number of generations in the GC
	static int GetGenerationCount() { return _Generations.size(); }	
// Sets the total bytes that have been allocated by the garbage collector
	static void SetTotalBytesAllocated( int Value ) { BytesAllocated = Value; }
};

void* operator new( const size_t sz, void** pVoid );

#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


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions