← Patterns

Shared ownership

12345678910111213#include <memory> #include <utility> struct foo {}; void func(std::shared_ptr<foo> obj) { } int main() { std::shared_ptr<foo> obj = std::make_shared<foo>(); func(obj); }

This pattern is licensed under the CC0 Public Domain Dedication.

Requires c++11 or newer.


Share ownership of a dynamically allocated object with another unit of code.


On line 11, we create a std::shared_ptr which has ownership of a dynamically allocated foo object (allocated with the std::make_shared utility function). Line 12 then demonstrates sharing ownership of this object with a function. That is, both main and func have access to the same foo object. When ownership of an object is shared, it will only be destroyed when all std::shared_ptrs owning it are destroyed.

In other cases, you may instead wish to transfer unique ownership of an object.


  • Joseph Mansfield

Last Updated

27 August 2018


Fork this pattern on GitHub