| CARVIEW |
Select Language
HTTP/2 200
date: Tue, 30 Dec 2025 15:56:48 GMT
content-type: text/html; charset=utf-8
server: cloudflare
last-modified: Mon, 05 Jul 2021 23:22:32 GMT
vary: Accept-Encoding
access-control-allow-origin: *
nel: {"report_to":"cf-nel","success_fraction":0.0,"max_age":604800}
expires: Tue, 30 Dec 2025 16:06:47 GMT
cache-control: max-age=600
report-to: {"group":"cf-nel","max_age":604800,"endpoints":[{"url":"https://a.nel.cloudflare.com/report/v4?s=HGSsTuhszg7Q%2FXHSrLFDNWgOUKza1BgVYhaP1r4I5iy0nItZtrCJlpxsesXYwo7sZBwvr7L%2BlhWo1Zp%2BVQSjqCBkjdRxXSkRSUzJ0D1%2Bfg%3D%3D"}]}
x-proxy-cache: MISS
x-github-request-id: 27B2:28476D:66B2A25:6FDB1C4:6953F63F
cf-cache-status: DYNAMIC
content-encoding: gzip
cf-ray: 9b62baaa0dfd3a1f-BOM
alt-svc: h3=":443"; ma=86400
Shared ownership - C++ Patterns
← 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.
Intent
Share ownership of a dynamically allocated object with another unit of code.
Description
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.