Atomic Smart Pointers
Get introduced to 'std::shared_ptr' template.
A std::shared_ptr consists of a control block and its resource. The control block is thread-safe, but access to the resource is not. This means modifying the reference counter is an atomic operation and you have the guarantee that the resource is deleted exactly once. These are the guarantees std::shared_ptr
gives you.
🔑 The importance of being thread-safe
I want to take a short detour to emphasize how important it is that the
std::shared_ptr
has well-defined multithreading semantics. At first glance, the use of astd::shared_ptr
does not appear to be a sensible choice for multithreaded code. It is by definition shared and mutable and is the ideal candidate for non-synchronized read and write operations and hence for. On the other hand, there is the guideline in modern C++: Don’t use raw pointers. This means, consequently, that you should use smart pointers in multithreaded programs. undefined behavior All bets are open. Your program can produce the correct result, the wrong result, crashes during run-time, or may not even compile. That behavior might change when porting to a new platform, upgrading to a new compiler or as a result of an unrelated code change.
Get hands-on with 1400+ tech skills courses.