How do shared pointers know how many pointers point to that object? (shared_ptr, in this case)
How do shared pointers know how many pointers point to that object? (shared_ptr, in
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Basically,
shared_ptrhas 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 ashared_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 noshared_ptrs point to it anymore.The weak reference count is used to support
weak_ptr; basically, any time aweak_ptris created from theshared_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.