Part 5/7:
For scenarios where multiple parts of your code need to share ownership of an object, shared_ptr
is the optimal choice. As opposed to unique_ptr
, multiple shared_ptr
s can point to the same object, using a reference counter to manage ownership.
Here's a basic example:
std::shared_ptr<Dog> dog = std::make_shared<Dog>();
doSomethingWithDog(dog);
This enables various functions to operate on the same shared_ptr
without the worry of premature deletion. When all instances of a shared_ptr
go out of scope and are no longer needed, the object is automatically cleaned up.