kildom / cppUtils

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

Avoid stack overflow when deallocating long chain of references #8

Open kildom opened 1 month ago

kildom commented 1 month ago

For example: single-linked list. If we deallocate first element, the deallocation of the second is called, then third and so on. This may lead to stack overflow for long lists. Instead deallocation of other objects should be postponed after exit from destructor.

Deallocation procedure:

if (!deallocationFlag) {
    DeallocationFlagGuard guard; // sets deallocationFlag in constructor and clears it in destructor
    delete ptr;
    while (deallocationList) {
        delete deallocationList.pop();
    }
    // If exception happens and deallocationList is not empty, it will be handled on the next deallocation or before GC
    // Generally, desrtuctors should not throw an exception.
} else {
    deallocationList.add(ptr);
}