Search code examples
c++c++11shared-ptrsmart-pointers

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?


Solution

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