Sobes.tech
Junior — Middle

Какова цель использования std::weak_ptr в управлении объектами в C++?

sobes.tech AI

Answer from AI

std::weak_ptr in C++ is used to hold a non-owning (weak) reference to an object managed by std::shared_ptr. Its main purpose is to avoid cyclic references, which can lead to memory leaks.

When multiple shared_ptrs refer to each other, they can form a cycle, and the reference count will never reach zero, preventing the object from being deleted. weak_ptr does not increase the reference count but allows checking if the object still exists and accessing it by converting to shared_ptr.

Example usage:

#include <memory>
#include <iostream>

struct Node {
    std::shared_ptr<Node> next;
    std::weak_ptr<Node> prev; // weak reference to avoid cycle
};

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 count
}

Thus, std::weak_ptr helps manage object lifetime and prevents memory leaks caused by cyclic dependencies.