4 ms·
std::shared_ptr is not thread safe, only the control block shared between all of the std::shared_ptr objects is thread safe. This means you only get a locking p
by nly 13y ago
std::shared_ptr is not thread safe, only the control block shared between all of the std::shared_ptr objects is thread safe. This means you only get a locking penalty when shared_ptr objects are constructed, copied, or destroyed, but not moved, dereferenced, or casted.
Both construction and destruction will allocate or can release memory, respectively, which I would think would bottleneck before any atomics or memory barriers inside shared_ptr. To me, the first likely port of call for improving performance in these cases is therefore a custom memory allocation strategy like a memory pool.
Copying can be a concern, but most containers and standard algorithms should be move aware now. You should be moving shared_ptr's far more often than you copy them.
All that aside, thread-safe by default seems to be the sane decision in this era.