Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why atomic overloads for shared_ptr exist

Why are there are atomic overloads for shared_ptr as described here rather than there being a specialization for std::atomic which deals with shared_ptrs. Seems inconsistent with the object oriented patterns employed by the rest of the C++ standard library..

And just to make sure I am getting this right, when using shared_ptrs to implement the read copy update idiom we need to do all accesses (reads and writes) to shared pointers through these functions right?

like image 542
Curious Avatar asked Mar 12 '23 20:03

Curious


1 Answers

Because:

std::atomic may be instantiated with any TriviallyCopyable type T.

Source: http://en.cppreference.com/w/cpp/atomic/atomic

And

std::is_trivially_copyable<std::shared_ptr<int>>::value == false;

Thus, you cannot instantiate std::atomic<> with std::shared_ptr<>. However, automatic memory management is useful in multi-threading, thus those overloads were provided. Those overloads are most likely not lock-free however (one of the big draws of using std::atomic<> in the first place); they probably use a lock to provide synchronicity.

As for your second question: yes.

like image 86
user2296177 Avatar answered Mar 20 '23 17:03

user2296177