Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Implement a Garbage Collector in C++ [duplicate]

Possible Duplicate:
How to implement garbage collection in C++

I was recently asked this question in an interview about how to implement a garbage collector in c++.

My answer was to have a pre allocated memory pool and construct object in that allocated space. Also to store the size of the memory allocated to an object in the byte preceding the memory location at which the pointer is pointing to.

The interviewer wasnt satisfied by the answer.

I later realized that my solution was actually trying to avoid the main goal of garbage collector by preallocating a memory pool and working with that memory.

But i think it would be difficult to implement a garbage collector in C++ without having to modify the compiler.

Any suggestions? Thanks in advance!!!

EDIT It seems that someone else too came faced the similar problem and loads of brainy guys have shed their views here

like image 696
Amm Sokun Avatar asked Oct 11 '22 18:10

Amm Sokun


1 Answers

You can read about the shared_ptr struct.

It implements a simple reference-counting garbage collector.

If you want a real garbage collector, you can overload the new operator.

Create a struct similar to shared_ptr, call it Object.

This will wrap the new object created. Now with overloading its operators, you can control the GC.

All you need to do now, is just implement one of the many GC algorithms

like image 137
Yochai Timmer Avatar answered Nov 15 '22 10:11

Yochai Timmer