January 2018
Intermediate to advanced
374 pages
9h 53m
English
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, ...