Shloim Shloim - 1 month ago 11
C++ Question

Can I copy a single shared_ptr simultaneously?

I know that copying and reseting a single

shared_ptr
in 2 separate threads is problematic, but what about 2 threads who try to create a copy of the same
shared_ptr
object. Does it need synchronization? Will the reference counter work properly here?

std::shared_ptr<T> global_t(new T());

// Thread 1
std::shared_ptr<T> t1(global_t);
do something with t1

// Thread 2
std::shared_ptr<T> t2(global_t);
do something with t2

Answer

A std::shared_ptr is always internally synchronized, so concurrent copying is ok (though might be less performant). And the managed object is only freed when its refcount drops to zero.

Which is the reason your first scenario has two possible defined results, instead of being UB: First resetting and then copying a reset shared_ptr, or first copying and then resetting the original shared_ptr.