How do shared pointers know how many pointers point to that object? (shared_ptr, in this case)
Basically, shared_ptr
has two pointers: a pointer to the shared object and a pointer to a struct containing two reference counts: one for "strong references," or references that have ownership, and one for "weak references," or references that don't have ownership.
When you copy a shared_ptr
, the copy constructor increments the strong reference count. When you destroy a shared_ptr
, the destructor decrements the strong reference count and tests whether the reference count is zero; if it is, the destructor deletes the shared object because no shared_ptr
s point to it anymore.
The weak reference count is used to support weak_ptr
; basically, any time a weak_ptr
is created from the shared_ptr
, the weak reference count is incremented, and any time one is destroyed the weak reference count is decremented. As long as either the strong reference count or the weak reference count is greater than zero, the reference count struct will not be destroyed.
Effectively, as long as the strong reference count is greater than zero, the shared object will not be deleted. As long as the strong reference count or the weak reference count is not zero, the reference count struct will not be deleted.