shared_ptr and weak_ptr Shared Ownership
Share ownership with reference counting and break cycles with weak_ptr.
Sharing an Object
Sometimes multiple parts of the program need to keep an object alive. std::shared_ptr<T> handles shared ownership with reference counting.
Creating a shared_ptr
Use std::make_shared — it allocates the control block and object in one allocation.
#include <memory>
auto s = std::make_shared<Widget>(42);
std::cout << s.use_count(); // 1All lessons in this course
- Why Smart Pointers Replace Raw new delete
- unique_ptr Exclusive Ownership
- shared_ptr and weak_ptr Shared Ownership
- Custom Deleters and Make Functions