How does std::shared_ptr work, and how is the reference counter synchronized between objects?
Last updated
std::shared_ptrshares a separately allocated control block holding the strong count, weak count, managed pointer, and deleter.Copies increment the strong count and destruction decrements it. At 0 the object is destroyed, and the control block lives until the weak count also reaches 0.
Counts are updated atomically, so copying/destroying across threads is safe. The pointee and the
shared_ptrinstance itself are not synchronized and need your own locking.