Why does the C++ standard include an atomic_store
or atomic_load
overload for shared_ptr
, but not weak_ptr
?
Is this just an oversight, or is there an actual reason for not providing atomic operations for weak_ptr
?
Using weak_ptr and shared_ptr across threads is safe; the weak_ptr/shared_ptr objects themselves aren't thread-safe. You can't read/write to a single smart pointer across threads.
To implement weak_ptr , the "counter" object stores two different counters: The "use count" is the number of shared_ptr instances pointing to the object. The "weak count" is the number of weak_ptr instances pointing to the object, plus one if the "use count" is still > 0.
(since C++11) std::weak_ptr is a smart pointer that holds a non-owning ("weak") reference to an object that is managed by std::shared_ptr. It must be converted to std::shared_ptr in order to access the referenced object.
By using a weak_ptr , you can create a shared_ptr that joins to an existing set of related instances, but only if the underlying memory resource is still valid. A weak_ptr itself does not participate in the reference counting, and therefore, it cannot prevent the reference count from going to zero.
This seems to be an oversight. There is a C++(17?) standard design proposal by Herb Sutter for atomic_shared_ptr/atomic_unique_ptr/atomic_weak_ptr, the document also explains the drawbacks of the existing approach with free funcitons atomic_load/atomic_store for shared_ptr: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4162.pdf
Presumably the answer is because, in order to use a weak_ptr
, you first convert it to a shared_ptr
using lock()
. Once you have that shared_ptr
you can use the atomic operations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With