O'Reilly logo

C++ High Performance by Bjorn Andrist, Viktor Sehr

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required