The std::shared_ptr pointer

In most cases, std::unique_ptr{} should be used to allocate dynamic memory. In some use cases, however, std::unique_ptr{} is incapable of properly representing pointer ownership. Pointer ownership refers to who owns a pointer, or in other words, who is responsible for allocating, and more importantly, deallocating a pointer. In most cases, a single entity within a program is responsible for this task. There are, however, some use cases where more than one entity must claim responsibility for deallocating a pointer.

The most common scenario where more than one entity must claim ownership over a variable involves threading. Suppose you have two threads:

  • Thread #1 creates a pointer (and thus owns it)
  • Thread #2 uses ...

Get Hands-On System Programming with C++ 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.