Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toy Garbage Collection: Is operator new/delete enough?

I'm working on a learning project of mine (in C) and thought of migrating it to C++ for extra learning points. Part of it involves a garbage collection system for a specific family of objects that, in C, I'd normally implement with a big malloc/mmap and go with a simple naive mark-and-sweep (I can identify references and things like that already).

My problem is I was considering transporting that idea to C++ but don't feel secure enough about my understanding of its memory management scheme.

So far I considered allocating a big memory pool and overloading operators new and delete on a base class to call the grab/release functions of my memory pool, and then let the garbage collector's sweep phase delete the objects as it saw them. Is that enough? What are the hidden pitfalls I'm failing to see here?

Edit: to clarify, I'm able to figure out the lifespan of the allocated objects already, so there's no need to use the gc abi. The objects will seldomly be manipulated by c++ code and the code that uses them is able to inform th gc they're being used without any need to inspect the stack.

like image 970
Alexandre Araujo Moreira Avatar asked Nov 11 '22 18:11

Alexandre Araujo Moreira


1 Answers

If you're changing the classes why not have them inherit from a new base class that registers to a GC during construction and unregisters during destruction. The manager class will do the book keeping. The base class can be a template:

template <class parent> class BASE_GC {
    BASE_GC() {  /* register address and name*/}
    ~BASE_GC() {  /* unregister*/}
};

The parent class name can be derived from typeid(*this).name(). As the base class name includes the parent name.

like image 72
egur Avatar answered Nov 15 '22 11:11

egur