std::shared_ptr#include <memory> is a smart pointer that lets several pointers share ownership of its managed object. It keeps a count of how many std::shared_ptr#include <memory>s own the object and deletes the object when the count reaches zero. It is available from the memory header:
#include <memory>
std::shared_ptr#include <memory><int> a(new int(5));It behaves like a raw pointer:
std::shared_ptr#include <memory><std::string#include <string>> s(new std::string#include <string>("hello"));
*s; // "hello"
s->size(); // 5
s == nullptr; // falseCopying a std::shared_ptr#include <memory> adds an owner, and destroying one removes an owner. use_count() returns the number of owners:
std::shared_ptr#include <memory><int> a(new int(5));
a.use_count(); // 1
{
std::shared_ptr#include <memory><int> b = a;
a.use_count(); // 2
}
a.use_count(); // 1Creating std::shared_ptr#include <memory> performs two heap allocations: one for the managed object (with new), and one for the control block (holds the reference count). std::make_shared#include <memory>() does both in a single allocation:
std::shared_ptr#include <memory><int> a(new int(5)); // Two allocations.
std::shared_ptr#include <memory><int> b = std::make_shared#include <memory><int>(5); // One allocation.Note
Prefer std::make_shared#include <memory>() unless the object is large and outlived by std::weak_ptr#include <memory>.
A std::unique_ptr#include <memory> can be moved into a std::shared_ptr#include <memory>, but not the other way around:
std::unique_ptr#include <memory><int> u(new int(5));
std::shared_ptr#include <memory><int> s = std::move#include <utility>(u);Warning
Two objects that hold a std::shared_ptr#include <memory> to each other cannot reach a count of zero, so neither is deleted. Break the cycle by using std::weak_ptr#include <memory>.
Note
Prefer std::unique_ptr#include <memory> unless an object needs more than one owner.
Dan