A light-weighted GC in C++ (C++11) based on mark-and-sweep algorithm.
- Accurate GC
- Controllable collection
- Low memory consumption, compatible with other memory managements
- Allow multiple instances of
GarbageCollector
- Not thread-safe for now. Each instance of
GarbageCollector
should be only used in a single thread, do not pass the reference to its allocated objects to another thread.
- Create
TinyGC::GarbageCollector
object. - Call
newObject
method ofGarbageCollector
to create collectable object whose type is a subclass ofTinyGC::GCObject
. If the object holds references or pointers to otherGCObject
, they must override the virtual functionGCObject::GCMarkAllChildren
. The macroGCOBJECT
helps to generate the function. - Call
newContainer
method ofGarbageCollector
to create collectable object of C++ STL containers ofGCObject*
or its subclass pointers. The wrapper class isTinyGC::GCContainer<C>
- Call
newValue
method ofGarbageCollector
to create collectable object of other C++ classes. The wrapper class isTinyGC::GCValue<T>
- Call
TinyGC::make_root_ptr
create a root pointer as a local or static variable. - Call
checkPoint
method ofGarbageCollector
to collect garbage if required.
Java:
class Point
{
Point(Integer x, Integer y) {
this.x = x;
this.y = y;
}
Integer x, y;
}
Point p = new Point(5, 6); // implicitly boxing
C++ with TinyGC:
class Point : public TinyGC::GCObject
{
using Integer = TinyGC::GCValue<int>*;
public:
Point(Integer x, Integer y)
: x(x), y(y) {}
Integer x, y;
private:
GCOBJECT(Point, TinyGC::GCObject, x, y)
}
int main()
{
TinyGC::GarbageCollector GC;
{
auto p = TinyGC::make_root_ptr(GC.newObject<Point>(
GC.newValue<int>(5),
GC.newValue<int>(6)
));
}
GC.collect();
}
- For TinyGC,
GarbageCollector::newContainer
,GarbageCollector::newValue
andGarbageCollector::newObject
is the only correct way to create collectable objects。 - All the objects allocated by
GarbageCollector
are owned by theGarbageCollector
object. It will release all resources once go out of scope, therefore can be used within a function, as a non-static menber of class or as thread local. make_root_ptr
returns aGCRootPtr
smart pointer that would guarantee the object it points to will not be collected.- The storage of
GCObject
is made up of three pointers: a pointer to virtual table, a pointer to the nextGCObject
, and a pointer toGarbageCollector
who allocates it. While collecting garbage, the mark bit is compressed into the lowest bit of pointer. The storage ofGCRootPtr
is made up of three pointers, a pointer toGCObject
and two pointers to the previous and nextGCRootPtr
.
Apache License 2.0