Sobes.tech
Junior — Middle

Explain the working principle of reference counting and its use in memory management.

sobes.tech AI

Answer from AI

Reference counting is a memory management mechanism where each object keeps track of the number of active references to it. When a new reference to an object is created, the counter increases, and when a reference is deleted or becomes inaccessible, it decreases. Once the counter reaches zero, the object is considered unused and can be freed from memory.

This approach helps automatically manage the lifetime of objects, preventing memory leaks. However, reference counting has a drawback — it cannot correctly handle cyclic references, where objects refer to each other but are not used externally.

Example of usage in C++:

class SharedPtr {
    T* ptr;
    int* ref_count;
public:
    SharedPtr(T* p) : ptr(p), ref_count(new int(1)) {}
    SharedPtr(const SharedPtr& sp) {
        ptr = sp.ptr;
        ref_count = sp.ref_count;
        ++(*ref_count);
    }
    ~SharedPtr() {
        if (--(*ref_count) == 0) {
            delete ptr;
            delete ref_count;
        }
    }
};