Share Objects with std::shared_ptr

Learn to share objects with std::shared_ptr.

We'll cover the following

The std::shared_ptr class is a smart pointer that owns its managed object and maintains a use counter to keep track of copies. This recipe explores the use of shared_ptr to manage memory while sharing copies of the pointer.

Note: For more detail about smart pointers, see the introduction to the Manage allocated memory with std::unique_ptr recipe.

How to do it

In this recipe, we examine std::shared_ptr with a demonstration class that prints when its constructors and destructor are called:

  • First, we create a simple demonstration class:

Get hands-on with 1200+ tech skills courses.