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...