Share objects with std::shared_ptr
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 earlier in this chapter.
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:
struct Thing { string_view thname{ "unk" }; Thing() { cout << format("default ctor: {}\n", thname); } Thing(const string_view& n) : thname(n) { cout...