Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How do shared pointers know how many pointers point to that object? (shared_ptr, in this case)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
123 views
Welcome To Ask or Share your Answers For Others

1 Answer

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_ptrs 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...