Re:C++20 has been approved
by gpderetta on Wednesday September 09, 2020 @06:35AM
(#24419542)
formally the answer to the question of "is shared pointer thread safe" is "no": modifying a shared pointer (for example by assigning to it) while another thread is reading (or writing) is UB (unless all accesses are done via the now deprecated std::atomic_* operations.
It is true that the ref count is kept atomically, which allows accessing two distinct shared pointers that happen to point to the same object from different threads. This is pretty much a requirement to support the baseline
distinct object thread safety (aka "as safe as int), but it is not what the unqualified "thread safe" normally refers to.
/pedantic
Anyway, it is true that with shared_ptr sometimes you might end up paying for what you do not use, but doing otherwise would have made any use of shared_ptr in threaded applications extremely unsafe so it was felt that in this case the cost was worth it for a vocabulary type object.
It is true that the ref count is kept atomically, which allows accessing two distinct shared pointers that happen to point to the same object from different threads. This is pretty much a requirement to support the baseline distinct object thread safety (aka "as safe as int), but it is not what the unqualified "thread safe" normally refers to.
/pedantic
Anyway, it is true that with shared_ptr sometimes you might end up paying for what you do not use, but doing otherwise would have made any use of shared_ptr in threaded applications extremely unsafe so it was felt that in this case the cost was worth it for a vocabulary type object.