Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there no atomic_{store,load} for weak_ptr?

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?

like image 671
Collin Dauphinee Avatar asked Sep 06 '12 21:09

Collin Dauphinee


People also ask

Is Weak_ptr lock thread safe?

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.

How is Weak_ptr implemented?

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.

What is Weak_ptr in C++?

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

Why do we need Weak_ptr?

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.


2 Answers

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

like image 52
Max Galkin Avatar answered Sep 29 '22 02:09

Max Galkin


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.

like image 26
Lily Ballard Avatar answered Sep 29 '22 02:09

Lily Ballard