Home > Software engineering >  Why is the counter in std::shared_ptr atomic?
Why is the counter in std::shared_ptr atomic?

Time:07-26

The implementation of _Sp_counted_base uses atomic counters:

_Atomic_word  _M_use_count;     // #shared
_Atomic_word  _M_weak_count;    // #weak   (#shared != 0)

Why are the counters atomic but the pointer not? Is atomic-count necessary? Are there any examples of its necessity?

(Because std::shared_ptr is not thread-safe, so I consider atomic-count is not necessary.)

CodePudding user response:

Because std::shared_ptr is not thread-safe, so I consider atomic-count is not necessary.

Your premise is invalid because std::shared_ptr is thread-safe (to an extent). And that's why the reference counters are atomic. From cppreference:

To satisfy thread safety requirements, the reference counters are typically incremented using an equivalent of std::atomic::fetch_add with std::memory_order_relaxed (decrementing requires stronger ordering to safely destroy the control block).

Further reading: std::shared_ptr thread safety explained

CodePudding user response:

Your assumption about thread safety is false. std::shared_ptr supports atomic operations since C 11 (the standard in which it was added). See the documentation.

CodePudding user response:

The access to the data of the object pointed to by the shared_ptr is not automatically thread safe, although the programmer can make it thread safe by synchronising all access via a mutex.

The reference count of shared_ptrs to the shared object is, however sharable across threads. Without this if on thread releases a reference and another thread makes a reference, there is a risk of accessing a deleted object.

  • Related