kildom / cppUtils

Small C++ utility library inspired by high level languages like Python or JavaScript
0 stars 0 forks source link

Implement GC #7

Open kildom opened 1 month ago

kildom commented 1 month ago

Using dollar references, we can implement GC similar to Python. This should be optional feature.

There are few new things:

Example:

DOLLAR_CLASS(Foo);
class FooClass: public gc::Object /* or gc::VirtualObject */ {
    Array<int> ints;
    Array<Bar$> bars;
    Bar$N ref;
    Bar$ staticBars[16];
    void gcTraverse() {
        gc::step(ints); // step will actually not travel this array
        gc::step(bars); // step will enumerate the array
        gc::step(ref); // pretty obvious 
        for (auto bar : staticBars) {
            gc::step(bar);
        }
    }
    void gcDispose() {
        gc::unref(ints);
        gc::unref(bars);
        gc::unref(ref);
        for (auto& bar : staticBars) {
            gc::unref(bar);
        }
    }
    // if there are just "simple" refs (no staticBars) then all of this can be replaced by:
    GC_OBJECT(ints, bars, ref);
}

The algorithm:

Maybe following points are not needed:

Breaking references in the gcDispose causes deallocation of objects, so they will be removed from unreachable objects set (doubly-linked list). It will reduce number of gcDispose calls. To avoid list enumerator corruption, the object is removed from the list and added to a different one before call to gcDispose.

At the end, if the new list is non-empty, then it means that unreachable objects are not deallocates which indicates memory leak, we should call FAULT in this case.