Sobes.tech
Junior — Middle

How can cyclic references be avoided when using std::shared_ptr by applying std::weak_ptr?

sobes.tech AI

Answer from AI

Cyclic references occur when two or more objects managed by std::shared_ptr refer to each other, leading to a memory leak because the reference count never reaches zero.

To avoid this problem, std::weak_ptr is used — a weak reference that does not increase the reference count of the object. Usually, in a cycle, one of the references is made a std::weak_ptr to break the ownership cycle.

Example:

#include <memory>
#include <iostream>

struct Node {
    std::shared_ptr<Node> next;
    std::weak_ptr<Node> prev; // weak reference to avoid cycle
    ~Node() { std::cout << "Node destroyed\n"; }
};

int main() {
    auto first = std::make_shared<Node>();
    auto second = std::make_shared<Node>();

    first->next = second;
    second->prev = first; // weak_ptr does not increase the counter
}

Thus, std::weak_ptr allows referencing an object without increasing the reference count, preventing cyclic dependencies and memory leaks.