Fix C++ shared_ptr Cycle Leak — Two Objects Keep Each Other Alive, weak_ptr Breaks the Cycle
A Parent owns its Child, the Child owns its Parent, and neither object is ever destroyed. This guide builds that cycle, proves the leak with counts and a weak observer instead of guessing, and then breaks the cycle by turning one of the two links into a std::weak_ptr.
Written November 20, 2026 · Tested with GCC 13.3.0 · 13 min read
- The leak: two objects that own each other
- Why the count never reaches zero
- The fix: make the back link a std::weakptr
- What the weak link costs
Written November 20, 2026
Tested with GCC 13.3.0
What this guide is
std::shared_ptr destroys its object when the last std::shared_ptr that owns the object goes away. That rule has a hole in it. If object A holds a std::shared_ptr to object B, and object B holds a std::shared_ptr back to object A, then each object always has one owner left: the other object. The outside pointers can all be destroyed and both counts still sit at 1. Neither destructor runs. The pair stays in memory for the rest of the program.
Nothing reports this. There is no crash, no exception, and no warning at any single line, because every line does what it says. The leak shows up only in what never happens: a destructor that never runs, a file handle or socket inside the object that never closes, memory that grows each time the cycle is built. The fix is to make one of the two links non-owning. A std::weak_ptr refers to an object managed by std::shared_ptr without owning it, so it does not add to the count that keeps the object alive. Put the weak link on the direction that only looks back, and the counts can reach zero again.
Build every program in this guide with g++ -std=c++17 -g. The examples use std::make_shared, std::shared_ptr, and std::weak_ptr from the <memory> header, all available since C++11; C++17 is used here as a plain current baseline.
The leak: two objects that own each other
The reproducer is two classes. Parent holds a std::shared_ptr<Child> at line 9. Child holds a std::shared_ptr<Parent> at line 15. Both destructors print a line, so destruction is visible when it happens and its absence is visible when it does not. A std::weak_ptr<Parent> named observer sits outside the scope at line 20. A weak pointer can watch the object without keeping it alive, which makes it the right tool for the test: after the scope ends, the observer reports whether the Parent is still there.
#include <iostream>
#include <memory>
#include <string>
struct Child;
struct Parent {
std::string name = "parent-1";
std::shared_ptr<Child> child;
~Parent() { std::cout << "Parent destroyed" << std::endl; }
};
struct Child {
int id = 7;
std::shared_ptr<Parent> parent;
~Child() { std::cout << "Child destroyed" << std::endl; }
};
int main() {
std::weak_ptr<Parent> observer;
{
auto parent = std::make_shared<Parent>();
auto child = std::make_shared<Child>();
parent->child = child;
child->parent = parent;
observer = parent;
std::cout << "inside scope: parent use_count = " << parent.use_count() << std::endl;
std::cout << "inside scope: child use_count = " << child.use_count() << std::endl;
}
std::cout << "after scope: observer use_count = " << observer.use_count() << std::endl;
std::cout << "after scope: observer expired = " << std::boolalpha << observer.expired() << std::endl;
std::cout << "after scope: no destructor lines above means the pair leaked" << std::endl;
return 0;
}
$ g++ -std=c++17 -g cycle.cpp -o cycle
$ ./cycle
inside scope: parent use_count = 2
inside scope: child use_count = 2
after scope: observer use_count = 1
after scope: observer expired = false
after scope: no destructor lines above means the pair leaked
The program exits with status 0, and the output was the same in three runs. Read the counts in order. Inside the scope, each count is 2. The Parent is owned by the local variable parent and by child->parent. The Child is owned by the local variable child and by parent->child. Two owners each is correct at that point; the objects are in use.
The scope then ends and both local variables are destroyed. Each count drops by one, to 1. That is where the counts stop. The Parent still has one owner, the std::shared_ptr<Parent> stored inside the Child, and the Child still has one owner, the std::shared_ptr<Child> stored inside the Parent. For the Parent to be destroyed, the Child would have to be destroyed first, because only the Child's destruction releases child->parent. For the Child to be destroyed, the Parent would have to be destroyed first. Neither can go first, so neither goes at all.
The observer lines prove the pair survived. After the scope, observer.use_count() reports 1, the one owner left, which is the Child's link. observer.expired() reports false, which means the object it watches has not been deleted. And the output contains no Parent destroyed line and no Child destroyed line anywhere. The program reached the end of main and returned 0 with both objects still allocated. In a long-running program the same shape repeats: build the pair once per request or once per connection, drop the outside pointers, and the pairs pile up, each one holding whatever resources its members hold.
Why the count never reaches zero
use_count() returns the number of std::shared_ptr objects that own the managed object. Destruction is tied to that number: the object is destroyed when the last remaining owning std::shared_ptr is destroyed, or when the last one is assigned another pointer or reset. A cycle defeats the rule by construction. The last owner of each object is a member of the other object, and a member is released only when its own object is destroyed. The count can fall as outside pointers go away, but the final step, from 1 to 0, needs a destruction that itself needs the count to reach 0 first.
A std::weak_ptr does not take part in this count. It holds a non-owning reference to an object managed by std::shared_ptr. Creating one, copying one, or destroying one does not change use_count(), and a weak pointer on its own never keeps an object alive. That is the whole reason it can break the cycle: replace one owning link with a weak link and that direction stops contributing the count of 1 that blocks destruction.
The self-reference form is the same bug with one object instead of two. An object that holds a std::shared_ptr member which shares ownership of the object itself owns itself, so its count also stops at 1 and its destructor also never runs. The fix direction is the same: a self-link that only refers back must not be an owning link. Code that needs a std::shared_ptr to the current object from inside a member function has a separate mechanism for that, std::enable_shared_from_this, whose shared_from_this() returns pointers that share the existing ownership, as the example on the std::shared_ptr reference page shows.
The fix: make the back link a std::weak_ptr
The fixed program changes one line of the design. Parent still owns the Child through std::shared_ptr<Child> at line 9, because the Parent is the owner in this pair: the Child exists as part of the Parent. The Child's link back to the Parent becomes a std::weak_ptr<Parent> at line 15. The Child can still reach the Parent while the Parent is alive, through lock() at line 27, but the Child no longer keeps the Parent alive.
#include <iostream>
#include <memory>
#include <string>
struct Child;
struct Parent {
std::string name = "parent-1";
std::shared_ptr<Child> child;
~Parent() { std::cout << "Parent destroyed" << std::endl; }
};
struct Child {
int id = 7;
std::weak_ptr<Parent> parent;
~Child() { std::cout << "Child destroyed" << std::endl; }
};
int main() {
std::weak_ptr<Parent> observer;
{
auto parent = std::make_shared<Parent>();
auto child = std::make_shared<Child>();
parent->child = child;
child->parent = parent;
observer = parent;
if (auto locked = child->parent.lock()) {
std::cout << "inside scope: child reached parent named " << locked->name << std::endl;
} else {
std::cout << "inside scope: child could not reach parent" << std::endl;
}
std::cout << "inside scope: parent use_count = " << parent.use_count() << std::endl;
std::cout << "inside scope: child use_count = " << child.use_count() << std::endl;
}
std::cout << "after scope: observer use_count = " << observer.use_count() << std::endl;
std::cout << "after scope: observer expired = " << std::boolalpha << observer.expired() << std::endl;
return 0;
}
$ g++ -std=c++17 -g fixed.cpp -o fixed
$ ./fixed
inside scope: child reached parent named parent-1
inside scope: parent use_count = 1
inside scope: child use_count = 2
Parent destroyed
Child destroyed
after scope: observer use_count = 0
after scope: observer expired = true
This program also exits with status 0, with the same output in three runs. The counts inside the scope show the change. The Parent's count is 1, not 2: only the local variable owns it, because the Child's weak link adds nothing. The Child's count is still 2, owned by the local variable and by the Parent, which is correct, since the Parent does own the Child.
The first line shows the weak link in use. A std::weak_ptr cannot be dereferenced directly; it must be converted to a std::shared_ptr first, and lock() is the conversion used here — unlike constructing a std::shared_ptr from the std::weak_ptr directly, which throws when the object is already gone, lock() returns an empty std::shared_ptr in that case. Because the Parent is alive at that point, lock() returns a std::shared_ptr that manages the Parent, the test passes, and the program prints the Parent's name, parent-1, read through the locked pointer. While that locked pointer exists it is a real owner, so code holding it can use the object safely even if the last other owner goes away in the meantime; the object's lifetime extends until the temporary std::shared_ptr is destroyed.
At the end of the scope the local variables are destroyed and this time nothing holds the pair up. The local child goes first and drops the Child's count to 1. The local parent then drops the Parent's count to 0, so the Parent is destroyed and prints Parent destroyed. Destroying the Parent destroys its std::shared_ptr<Child> member, which drops the Child's count to 0, so the Child is destroyed and prints Child destroyed. The order in the output, Parent first and then Child, follows from that chain. The observer then reports use_count 0 and expired true: the object it watched is gone, which is the result the first program failed to produce.
What the weak link costs
The weak direction gives up a guarantee, and code using it has to pay for that in one place. After the object is deleted, lock() returns an empty std::shared_ptr. Any code that follows a weak link must check the result of lock() before using it, the way line 27 does by putting the locked pointer in the if condition. Code that locks once and stores the result can use that one pointer for the whole operation. Code that checks expired() and then calls lock() as a separate step has a gap between the check and the use; the single lock() call and a test of its result is the form to copy, because the returned pointer itself either manages a live object or is empty.
expired() still has its place. It answers whether the referenced object was already deleted, and it is the right call when the code only needs to know, for example when pruning dead entries from a list of weak pointers. use_count() on a weak pointer returns the number of std::shared_ptr objects that manage the object, so it serves as a diagnostic, as the observer lines in both programs show. Neither call gives access to the object. Access goes through a conversion to std::shared_ptr — through lock() in this guide, whose result either manages a live object or is empty.
Picking which direction goes weak is a design question with a plain test. Ask which object owns the other. The owning direction stays std::shared_ptr: a parent owns its children, a document owns its sections, a cache owns its entries while they are cached. The direction that points back, up, or sideways for convenience — child to parent, section to document, entry to a listener that only observes — goes weak. A useful shortcut: if deleting object A should also delete object B, A holds the std::shared_ptr to B. If B should merely notice when A is gone, B holds the std::weak_ptr.
The manual break: resetting one link before the scope ends
A cycle already in code can also be broken by hand at a known teardown point. If some function reliably runs before the outside pointers go away, resetting one of the two links drops the count and lets normal destruction proceed. The third program is the first program with one added line, child->parent.reset() at line 27, called while both local variables are still alive:
#include <iostream>
#include <memory>
#include <string>
struct Child;
struct Parent {
std::string name = "parent-1";
std::shared_ptr<Child> child;
~Parent() { std::cout << "Parent destroyed" << std::endl; }
};
struct Child {
int id = 7;
std::shared_ptr<Parent> parent;
~Child() { std::cout << "Child destroyed" << std::endl; }
};
int main() {
{
auto parent = std::make_shared<Parent>();
auto child = std::make_shared<Child>();
parent->child = child;
child->parent = parent;
std::cout << "inside scope: parent use_count = " << parent.use_count() << std::endl;
std::cout << "inside scope: child use_count = " << child.use_count() << std::endl;
child->parent.reset();
std::cout << "after reset: parent use_count = " << parent.use_count() << std::endl;
}
std::cout << "after scope: both objects destroyed" << std::endl;
return 0;
}
$ g++ -std=c++17 -g rescue.cpp -o rescue
$ ./rescue
inside scope: parent use_count = 2
inside scope: child use_count = 2
after reset: parent use_count = 1
Parent destroyed
Child destroyed
after scope: both objects destroyed
The run exits with status 0 and repeated three times with the same output. The reset replaces the managed object of child->parent with an empty pointer, so the Parent's count falls from 2 to 1 while the scope is still open. From there the end of the scope works the normal way: the Parent's count reaches 0 when the local variable goes, the Parent is destroyed, and its member link releases the Child. This works, but it is the weakest of the three forms in this guide. It depends on the teardown call always running, on every path, including error paths. The weak link needs no teardown call at all, which is why it is the fix to reach for first and the manual reset is a rescue for code that cannot change its types yet.
Finding a cycle in real code
The reproducer points at its own bug. Real cycles hide inside larger graphs: a node points to its children and each child points back, a handler registers itself with an owner that it also owns a pointer to, a task holds its scheduler and the scheduler holds its tasks. Three checks find them.
First, watch the destructor. If a class manages a resource and its destructor stops running in tests or in logs while the program continues, suspect a cycle before suspecting the logging. A counter incremented in the constructor and decremented in the destructor, compared at a point where no objects should exist, turns that suspicion into a number.
Second, add the observer test from the first program. Keep a std::weak_ptr to an object that should be short-lived, let the owning pointers go away, and read expired() and use_count(). expired false with a count of 1 or more, at a point where the code believes nothing owns the object, means something inside the graph still owns it. Printing that count at a few points in the object's life narrows down which link it is.
Third, read the member lists as a graph. List, for each class in the suspect group, which members are std::shared_ptr to which other classes in the group. A closed loop of owning links in that list is a cycle waiting for the objects to be connected at run time. Loops that pass through a std::weak_ptr, a raw pointer, or a reference do not hold the objects up, so the audit is only about the owning links. When the audit finds a loop, the observer test settles whether that loop is the leak: connect the objects the way the program does, drop the outside pointers, and read the count.
The fixes, ranked
- First, make the back link a
std::weak_ptr. The child-to-parent, entry-to-owner, node-to-observer direction is the one that only refers, so it is the one that stops owning. - Second, where a back link is not needed at all, remove it and pass the parent as a parameter or a reference at call time instead of storing a pointer.
- Third, as a rescue in code whose types cannot change yet, reset one link at a teardown point that runs on every path, and treat that call as temporary until the weak link lands.
- Fourth, audit the rest of the group for other closed loops of
std::shared_ptrmembers. Fixing one loop leaves any second loop leaking the same way. - Fifth, add the weak observer test to the tests for the pair, so a future edit that turns the weak link back into a
std::shared_ptrfails a test instead of leaking quietly.
Which fix for which cause
| Cause | Shape of the leak | Fix |
|---|---|---|
| Parent and child own each other | Both counts stop at 1 | weak_ptr on the back link |
| Object holds a pointer to itself | One count stops at 1 | weak_ptr, or shared_from_this |
| Observer only watches an object | Watcher keeps object alive | weak_ptr for the watcher |
| Teardown point always runs | Cycle known, types frozen | Reset one link at teardown |
| No back link is needed | Stored pointer never used | Drop the member, pass at call time |
Checklist
- Draw the owning links between the classes in the group. Any closed loop of
std::shared_ptrmembers is a leak once the objects connect. - Keep ownership in one direction only. The direction that points back or only observes is a
std::weak_ptr. - Check every
lock()result before use. After the object is gone,lock()returns an empty pointer, and the code must handle that case. - Lock once per operation and use that pointer throughout, instead of checking
expired()and locking as two separate steps. - Add a weak observer test for each pair that used to cycle: after the owners go away,
expired()must reporttrue. - Put a print or a counter in the destructor while hunting a suspected cycle, and remove it once the counts behave.
- Remember that
std::make_shareddoes not change any of this. It builds the object and its control block in one allocation; the cycle is in the links between objects, not in how each object was created.
Related guides on this site
- Fix LeakSanitizer "Detected Memory Leaks" — Direct vs Indirect Leaks, Traced to the Owner — the leak-report companion, for reading a LeakSanitizer report and tracing direct and indirect leaks back to the code that owns the memory.
- Reading an AddressSanitizer Heap-Use-After-Free — Fault, Freed-By, Allocated-By — the opposite lifetime error, where an object is used after it was destroyed instead of never being destroyed at all.
- C++ Pointers and References: Addresses, Dereferencing, and nullptr — the pointer basics companion, covering addresses, dereferencing, and null pointers underneath the smart pointer types used here.
Sources
- cppreference, std::shared_ptr — for
std::shared_ptrretaining shared ownership of an object, for the object being destroyed when the last remaining owningshared_ptris destroyed or is assigned another pointer viaoperator=orreset(), foruse_count()returning the number ofshared_ptrobjects referring to the same managed object, forstd::make_sharedcreating the control block and the managed object with a single allocation, and for the destructor decrementing the number of shared owners and calling the managed object's destructor when that counter reaches zero. - cppreference, std::weak_ptr — for
std::weak_ptrholding a non-owning reference to an object managed bystd::shared_ptr, for it having to be converted tostd::shared_ptrin order to access the referenced object, for usingstd::weak_ptrto break reference cycles formed by objects managed bystd::shared_ptrwhere an orphaned cycle's reference counts cannot reach zero and the memory is leaked, for one of the pointers in the cycle being made weak to prevent that, and for theuse_count,expired, andlockmember functions.
Keep Exploring
Seven tips and seven puzzles so far, each one a short runnable example with the fix explained.
Paste an AddressSanitizer, UBSan, or ThreadSanitizer report and get the bug, the file and line, and the fix \u2014 in plain language.
C++20 and C++23 features, migration paths, and measured trade-offs.
The full C++ hub \u2014 language basics, the standard library, coroutines, and measured comparisons.
Paste a [Service] section and get a plain-language verdict on every sandboxing setting it finds.