3

Is there a class that does garbage collection for C++. I was thinking something like:

class A : public GarbageCollected<A>
{
  void kill()
  {
     GarbageCollected<A>.set_cleanup_flag();
  }
  ...
private:
  GarbageCollectedPointer<B> b_pointer; // Somehow we follow 
  GarbageCollectedPointer<B> b_pointer2; // these pointers.
};

class B
{
  ...
};

class GarbageContainer
{
  ...
};

int main()
{
  GarbageContainer gc;
  gc.add(new A());
  ...
}

The idea being that GarbageContainer would do mark and sweep on the objects or some other garbage collection method. It would save having to do reference counting and using weak_ptrs and garbage collection could be used just for objects it is felt necessary.

Are there any libraries that implement something like this?

Clinton
  • 22,361
  • 15
  • 67
  • 163
  • 7
    Before even going there, stop and think why you need it. Every time somebody wanted a GC in C++ meant their design was wrong. – Gene Bushuyev Jun 19 '11 at 16:03
  • 3
    @Gene: you should probably tell Hans Boehm and Bjarne Stroustrup that. Both of them are keen to get mark/sweep-style GC into C++. – Steve Jessop Jun 19 '11 at 16:54
  • 2
    I like to think of `smart pointers` as `fine grain deterministic garbage collectors`. – Martin York Jun 19 '11 at 16:59
  • 1
    @Steve Jessop: I think I understand their motivation and I disagree with them. There are already languages for people who want GC. In C++ I think the efforts should be directed in strengthening value semantics, not trying to cover landmines of pointer semantics. – Gene Bushuyev Jun 20 '11 at 00:44
  • There is a comparison of many of the solutions available on SO [here](http://stackoverflow.com/questions/81062/garbage-collectors-for-c). – alternative Jun 19 '11 at 15:39

3 Answers3

2

C++0x supports shared_ptr that uses reference counting to keep track of memory allocation. If used carefully, it serves as a good garbage collector.

The shared_ptr deallocates the memory when there are no objects left referring to a memory block (reference count has reached 0).

Sandeep
  • 648
  • 5
  • 12
1

Look up Boehm's garbage collector. I don't think it has multiple GC containers out of the box, but you can add this feature yourself if you absolutely need it.

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243
0

libgc is a good option for garbage collection library in C/C++

Alok Save
  • 202,538
  • 53
  • 430
  • 533