Interview Question

How do you avoid shared_ptr cycles?

Use weak_ptr for non-owning links that would otherwise form shared ownership cycles.

💡 Concept ✅ Quick Revision 🧠 C++

Answer

Break shared_ptr ownership cycles by making at least one relationship non-owning with std::weak_ptr. • A cycle keeps every control block’s strong reference count above zero. • weak_ptr observes a shared object without extending its lifetime. • Call lock to obtain a temporary shared_ptr only when the object is still alive.

💡 C++ Example

struct Parent; struct Child { std::weak_ptr<Parent> parent; }; struct Parent { std::shared_ptr<Child> child; };

⚡ Quick Revision

Use weak_ptr for non-owning links that would otherwise form shared ownership cycles.