...

/

Share Objects with std::shared_ptr

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:

struct Thing {
string_view thname{ "unk" };
Thing() {
cout << format("default ctor: {}\n", thname);
}
Thing(const string_view& n) : thname(n) {
cout << format("param ctor: {}\n", thname);
}
~Thing() {
cout << format("dtor: {}\n", thname);
}
};

This ...