Using shared_ptr in a multithreaded environment

What about the std::shared_ptr? Can it be used in a multithreaded environment, and how is the reference counting handled when multiple threads are accessing an object referenced by multiple shared pointers?

To understand shared pointers and thread safety, we need to recall how std::shared_ptr is typically implemented (see also Chapter 7, Memory Management). Consider the following code:

// Thread 1 
auto p1 = std::make_shared<int>(int{42}); 

The code creates an int on the heap and a reference-counted smart pointer pointing at the int object. When creating the shared pointer with std::make_shared(), a control block will be created next to the int. The control block contains, among other things, ...

Get C++ High Performance now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.