Search code examples
c++multithreadingc++11shared-ptratomic

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

Solution

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