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
{
...
};
c开发者_Go百科lass 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?
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).
- This tutorial on shared_ptr should get you started.
- Here is an advanced tutorial on shared_ptr internals
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.
libgc is a good option for garbage collection library in C/C++
精彩评论