Learning Hub Search Ctrl K

Modern C++ › C++11

shared_ptr and weak_ptr

Shared ownership, reference cycles and weak references.

Since C++11 intermediate #shared_ptr#weak_ptr#make_shared#reference-counting#ownership#cycles

Explanation

std::shared_ptr<T> (header <memory>) provides shared ownership: several pointers co-own an object, and it is destroyed when the last owner goes away. It stores a pointer to the object and a pointer to a control block holding the strong count, the weak count, and the deleter. The count updates are atomic, so copying shared_ptrs across threads is safe (the pointee itself is not synchronized).

std::weak_ptr<T> observes an object without owning it. lock() returns a shared_ptr (empty if the object is gone). Its job is to break reference cycles and to implement caches and back-pointers.

Create them with std::make_shared<T>(args...): one allocation for object plus control block, and exception-safe.

Default to unique_ptr; reach for shared_ptr only when ownership truly is shared.

Example

#include <iostream>
#include <memory>
#include <string>
#include <vector>

struct Node {
    std::string name;
    std::weak_ptr<Node> parent;                         // weak: no ownership cycle
    std::vector<std::shared_ptr<Node>> children;
    explicit Node(const std::string& n) : name(n) { std::cout << "+" << name << "\n"; }
    ~Node() { std::cout << "-" << name << "\n"; }
};

int main() {
    auto root  = std::make_shared<Node>("root");
    auto child = std::make_shared<Node>("child");
    child->parent = root;
    root->children.push_back(child);

    std::cout << root.use_count() << " " << child.use_count() << "\n";   // 1 2

    if (auto p = child->parent.lock())                  // promote weak -> shared
        std::cout << "parent is " << p->name << "\n";

    std::weak_ptr<Node> observer = child;
    child.reset();                                      // drop our owner
    std::cout << observer.expired() << "\n";            // 0: root still owns it
    root.reset();                                       // destroys root, then child
    std::cout << observer.expired() << "\n";            // 1
    return 0;
}

Common pitfalls

  • Reference cycles (A owns B owns A) are never freed. Make one direction a weak_ptr.
  • Never construct two shared_ptrs from the same raw pointer: two control blocks, double delete. Copy the shared_ptr, or use enable_shared_from_this.
  • shared_ptr<T>(new T) plus a throwing argument in the same expression can leak; prefer make_shared.
  • Passing shared_ptr by value everywhere costs atomic increments; take const T& or T* when you don’t need ownership.
  • use_count() is a hint under concurrency, not a reliable synchronization tool.

Legacy vs modern

This standardizes boost::shared_ptr / weak_ptr from C++03 (see Smart Pointers before C++11). Migration is typically boost:: → std::, plus make_shared. C++17 adds shared_ptr<T[]>.

Exercises

1. A Parent holds shared_ptr<Child> and each Child holds shared_ptr<Parent>. What goes wrong?

They keep each other alive forever (leak). Change the child’s pointer to weak_ptr<Parent>.