As a C++ lead, when would you allow std::shared_ptr in a codebase, and what rules would you set for its use?
answer
- unique ownership is the default
- lifetime decided at run time
- weak back-edges by rule
- const for cross-thread sharing
- where the last release lands
basics
~20 sDefault to unique ownership and allow std::shared_ptr only where lifetime is genuinely decided at run time by several parties, such as async callbacks, caches and immutable snapshots, with rules for weak back-edges, const pointees and borrowing instead of copying.
solid answer
~50 sI would make single ownership the default and treat `std::shared_ptr` as a design decision that needs a reason: several parties keep the object alive and nobody can know statically which finishes last — in-flight async operations, caches whose entries readers may still hold, immutable snapshots shared across threads. Then rules: every back-edge or observer edge is a `std::weak_ptr`; shared data crossing threads is `std::shared_ptr<const T>`, replaced rather than mutated; functions that only use the object take `const T&`, and `shared_ptr` is copied only where ownership is really taken; `enable_shared_from_this` only for objects that keep themselves alive across callbacks; and shared types keep their destructors cheap, because the last release runs it on whatever thread drops it. The trade-off is author convenience against hidden graphs, cycles, nondeterministic destruction and atomic-count cost, so reviews ask "who else owns this, and why?".
go deeper
Learn your team's rule for when shared_ptr is allowed, and default to a single owner otherwise.
Recognize the cases that genuinely need shared ownership - async operations, caches with readers, snapshots - and use weak_ptr for observers.
Review shared ownership in designs: find cycles, needless copies, mutable shared state across threads and heavy destructors on I/O threads.
Set where shared ownership is allowed, how it is reviewed, and when handles or single ownership are the better trade for the system's lifetime model.
## Why the policy is a lead's call `std::shared_ptr` removes one question from the author — "when is this deleted?" — and moves it into the running program. That is exactly right for some objects and quietly expensive for others. Each use adds a control block, two-pointer handles, atomic count updates on every copy, the possibility of cycles, and a destructor that runs on whichever thread happens to release last. A codebase where `shared_ptr` is the default hides its ownership graph; a codebase that bans it reinvents reference counting badly where it was needed. The lead decides where the line sits. ## When shared ownership is the honest answer - **Asynchronous operations.** A chat session is held by a registry and by in-flight I/O callbacks; whichever finishes last must free it, and that order is not known when the code is written. - **Caches and registries with outstanding readers.** An entry can be evicted while a reader still uses it; the reader's `shared_ptr` keeps it alive until the read ends. - **Immutable snapshots.** A configuration or routing table published to many threads as `std::shared_ptr<const T>`, replaced as a whole, freed when the last reader moves on. And when it is not: - an object with one obvious owner (a parent owning its children, a service owning its connections); - a parameter the callee only uses during the call; - convenience — "so nobody has to think about lifetime". ## Rules to set 1. **Default to values and `std::unique_ptr`;** a `shared_ptr` member or return type needs a one-line reason in review. 2. **Weak back-edges by rule.** Observer lists, parent pointers and registries that must not pin hold `std::weak_ptr` and promote with `lock()`. 3. **`const` across threads.** Shared data crossing threads is `std::shared_ptr<const T>`; changes publish a new object. 4. **Borrow, don't copy.** Functions that only use the object take `const T&` or `T*`; `shared_ptr` is copied or moved only where ownership is taken. 5. **`enable_shared_from_this` only for self-keepalive** across callbacks, with factory-only creation. 6. **Cheap destructors for shared types**, or a hand-off of heavy cleanup to a dedicated queue. ## Trade-offs to weigh | choice | gains | costs | |---|---|---| | `shared_ptr` by default | authors never decide lifetimes | hidden graphs, cycles, atomic counting everywhere, unpredictable destruction point | | single ownership by default | explicit lifetimes, cheaper handles | design effort, borrows that can dangle and need review and sanitizers | | handles into a pool (index plus generation) | deterministic lifetime, stale access detected | lookup on every access, a pool to write and maintain | Game engines and other frame-based systems often prefer the third row for objects referenced from many systems; servers built on asynchronous I/O usually need the first for sessions and operations, and the second everywhere else. ## Where the destructor runs With `shared_ptr` the object is destroyed by whichever owner releases last, on that thread and inside that call. A session whose final owner is an I/O callback is destroyed on the I/O thread; a heavy destructor stalls the event loop, and a destructor that takes a lock can deadlock with code that already holds it. A policy that allows shared ownership should say how shared types' destructors stay cheap. ## Migrating an over-shared codebase A codebase that already uses `shared_ptr` everywhere does not need a rewrite; it needs the ownership graph made visible: 1. For each `shared_ptr` member, ask who else holds the object. When the answer is "nobody, really", change the member to `std::unique_ptr` and the other users to borrows. 2. Turn back-edges and observer lists into `std::weak_ptr`, which fixes the cycles that a leak checker reports. 3. Change function parameters that only use the object from `std::shared_ptr<T>` by value to `const T&`, which removes atomic traffic without any ownership change. 4. Leave genuinely shared lifetimes alone, and document why each one is shared. ## Making it enforceable - Review checklists ask "who else owns this, and why?" for every new `shared_ptr` member. - Leak and cycle detection runs in CI under sanitizer builds and in long-running soak tests. - The count of `shared_ptr` members per module is tracked; growth is a design conversation, not a lint warning.
- Where does the destructor run when the last std::shared_ptr is released, and why does that matter for a policy?On whichever thread drops the last owner, inside whatever call did it. A session whose final owner is an I/O callback is destroyed on the I/O thread, so a heavy destructor stalls the event loop, and one that takes a lock can deadlock with code holding that lock. A policy can require cheap destructors for shared types or hand final cleanup to a dedicated queue.
- What would you use instead of shared_ptr for objects referenced by many systems in a frame-based engine?Often a handle: an index into a pool plus a generation counter, with the pool as the single owner and validation on each access. Lifetimes stay deterministic, there is no atomic counting, and a stale handle is detected instead of keeping the object alive. The cost is the lookup on access and the pool itself; `shared_ptr` stays for the few objects whose lifetime really is decided by whoever finishes last.
- Using shared_ptr everywhere removes the need to design ownership
- Every observer should hold a shared_ptr to stay safe
- shared_ptr makes the pointed-to object thread-safe
- The destructor runs on the thread that created the object
- A shared_ptr can never leak because it counts references