开发者

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

This question already has answers here: Closed 11 years ago.

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 interview开发者_Python百科er 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


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


I think the interviewer was looking for smart pointers as that's the best the language can do and even then it requires a certain amount of attention from the programmer. This isn't proper GC in the CS sense.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜