C++: Two separate `make_shared` calls to same object will create two separate and independent shared_ptr and its control block?

Viewed 466
  1. In the code below, my understanding is a and b are not sharing the ownership. Instead, they are two separate smart pointer, each of them has individual control block with ref_count = 1. Is my understanding correct?
std::shared_ptr<Foo> a = make_shared<Foo>();
std::shared_ptr<Foo> b = make_shared<Foo>();
  1. the correct way to use shared_ptr which share the ownership and increase ref_cnt is call make_shared once to initialize the memory and use copy/assign to increase the ref_cnt and share owernship. For example:
std::shared_ptr<Foo> a = make_shared<Foo>();
auto b = a;
auto b(a);

Are the two points I mentioned above correct?

Thank you in advance!

2 Answers

You are correct on all counts. Having the same object owned by more than one chain of shared_ptr objects is not a good idea.

std::make_shared<Foo> will new up Foo object and return you a shared ptr to that object. If you call std::make_shared, same thing happens again, you will have new'ed another (independent) Foo object.


Interesting aside: One instance where you can get (unexpected) sharing for uniquely defined objects are for string literals.

Related