std::weak_ptr Deep Dive (Non-Owning Observer & Cycle Breaking)

🔴 Advanced

📖 Definition & Why We Need It

std::weak_ptr<T> holds a non-owning reference to an object managed by std::shared_ptr without incrementing the strong reference counter. Its primary purpose is to **break cyclic shared_ptr references** (where Object A points to B and B points to A, causing permanent memory leaks).

🛠️ Accessing Target Data safely

A std::weak_ptr cannot directly access object methods. To access the object, call wPtr.lock(), which returns a temporary std::shared_ptr if the object is still alive, or a null shared_ptr if the object was destroyed.

💡 Complete Code Example: Breaking Circular Deadlocks

#include <iostream>
#include <memory>

struct Node {
    std::shared_ptr<Node> next;
    std::weak_ptr<Node> prev; // weak_ptr breaks cyclic reference leak!

    ~Node() { std::cout << "Node Destroyed\n"; }
};

int main() {
    auto n1 = std::make_shared<Node>();
    auto n2 = std::make_shared<Node>();

    n1->next = n2;
    n2->prev = n1; // Non-owning back link

    if (auto lockedParent = n2->prev.lock()) {
        std::cout << "Parent is still alive!\n";
    }

    return 0; // Both nodes correctly destroyed without memory leak!
}

👀 Expected Output

Parent is still alive!
Node Destroyed
Node Destroyed