Clinton
Clinton

Reputation: 23135

Is there a garbage collecting class for C++

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?

Upvotes: 3

Views: 464

Answers (3)

Sandeep
Sandeep

Reputation: 658

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).

Upvotes: 2

Alok Save
Alok Save

Reputation: 206518

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

Upvotes: 0

n. m. could be an AI
n. m. could be an AI

Reputation: 119857

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.

Upvotes: 1

Related Questions