std::shared_ptr — shared ownership via reference counting.
1#include <memory>23auto sp1 = std::make_shared<int>(42);4std::cout << sp1.use_count(); // 156{7 auto sp2 = sp1; // Share ownership8 std::cout << sp1.use_count(); // 29} // sp2 destroyed, count = 11011std::cout << sp1.use_count(); // 11213// Control block layout:14// [weak_count | shared_count | deleter | data]1516// make_shared allocates in one block (more efficient)17auto efficient = std::make_shared<MyClass>(args...);1819// Two allocations (less efficient)20std::shared_ptr<MyClass> two_alloc(new MyClass(args...));
Overhead: