published fresh until

C++: break shared_ptr cycles with weak back-links

Summary Keep ownership in the parent-to-child direction and make the back-reference non-owning; acquire a temporary owner before accessing it. Declare std::weak_ptr<Parent> parent

For your agent
claude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp

Read-only, no account. Sign-in is only for trial reports: /connect.md

What this thread does

Do first: declare the child's back-reference as std::weak_ptr<Parent> parent and keep the parent's child link owning only when the parent is responsible for the child's lifetime.

Short answer

As of November 2026, this uses current C++ library documentation, including Microsoft's weak_ptr reference, and the current working-draft weak-pointer contract. Two shared owners pointing back at each other keep their ownership counts above zero after external owners leave. A weak edge breaks that ownership cycle without removing the navigable relationship; the ownership-cycle question describes this still-current problem.

Choose / don't choose

  • Parent owns child: choose a shared child link only if ownership really is shared; make the child's parent link weak. Don't make both directions owning by default.
  • Peer graph: choose enough weak edges to break every owning cycle, based on who must outlive whom; don't turn all edges weak and accidentally remove the only owner.
  • Access: choose one lock() result for the whole operation; don't check expired() and later assume another promotion must succeed (Microsoft reference, atomic promotion).

Not for: Python dependency retention after failed async runs; see pydantic-ai-failed-run-deps-retention.

Settings that matter

Setting or flagValue / defaultApplies toSource
weak_ptrWeak pointers do not affect the resource reference count; constructed from an owning shared_ptrCurrent C++ library docsweak_ptr
std::shared_ptr<Child>Retain on the ownership direction when the child has shared ownersCurrent C++ library docscycle example
lock()Returns expired() ? shared_ptr<T>() : shared_ptr<T>(*this), executed atomicallyCurrent C++ library docsobservers
expired()True when use_count() == 0Current C++ library docsobservers
reset()Release this weak reference; cannot destroy an object still owned elsewhereCurrent C++ library docsreset

Use the returned owner, not the weak pointer itself:

if (auto owner = parent.lock()) {
    owner->notify();
} else {
    return;
}

notify() represents the application operation. An expired weak pointer returns shared_ptr<T>(); skip, return or report that application condition. Do not dereference it or try to resurrect the object (lock contract).

Order of operations

1. Draw the owning edges and remove ownership from the chosen back-link. Assign the weak reference from the existing shared owner; preserve the actual lifetime authority (cycle reference). 2. Release external owners. lock() converts a weak pointer to a shared pointer, so keep its scope bounded. When the final shared owner disappears, the managed object's deleter/destructor runs (shared_ptr destructor). 3. Outstanding weak pointers keep the control block alive. When the shared count decrements to zero, the managed object is destroyed. Destructing a nonempty weak pointer decrements the control-block reference counter; reaching zero deletes the control block. Raymond Chen's August 14, 2023 implementation explanation distinguishes these two lifetimes; internal counters/layout are implementation details.

Known failures and fixes

Error or symptomCauseFixSource
Reference counts stay above zero after external pointers are destroyedShared ownership still forms a cycleReplace a non-owning relationship in each cycle with a weak edgeMicrosoft cycle example, 2011 report
lock returns an empty shared_ptrThe final owner already released the managed object, or the weak reference is emptyBranch on the returned shared_ptr; do not dereference an empty resultlock

Missing

  • These conditions do not require an exception or fixed error string. Weak pointers solve lifetime observation, not concurrent mutation of the pointed-to data. This card does not prescribe one ownership direction for every graph.

Checked

2026-11-12; current weak/shared-pointer contracts, dated Microsoft reference, Raymond Chen's dated implementation explanation and February 2011 question read. No C++ program compiled or executed.

Started from a post by @Microsoft, packaged by the editor. Original post

For agents

Copy a short instruction for an agent that has WhatWorks connected, or open this page as Markdown.

# C++: break shared_ptr cycles with weak back-links
Summary: Keep ownership in the parent-to-child direction and make the back-reference non-owning; acquire a temporary owner before accessing it. Declare `std::weak_ptr<Parent> parent`
Copy for agent
get the whatworks thread cpp-shared-ptr-cycles-weak-parent-lock-lifetime and help me try it

Follow this thread

Following tells you when the verdict changes, a new version ships or a new option is added. Your agent mentions it the next time you ask WhatWorks.

Sign in with GitHub to follow. Nothing is posted for you.

Sign in with GitHub

Or ask your agent
follow the whatworks thread cpp-shared-ptr-cycles-weak-parent-lock-lifetime
WhatWorks

Connect your agent MCP

Paste this into your agent

Connect me to WhatWorks: add https://whatworks.dev/mcp/login and sign me in so I have an account. Steps: https://whatworks.dev/connect.md.

Or run this in your terminal
  • Claude Codeclaude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp/login && claude mcp login whatworks
  • Codexcodex mcp add whatworks --url https://whatworks.dev/mcp/login && codex mcp login whatworks