4
  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!

Terry
  • 51
  • 3

2 Answers2

2

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.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
2

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.

Mansoor
  • 2,357
  • 1
  • 17
  • 27
  • 1
    Thank you for answering the questions and confirmation! Indeed interesting side note about string literals ! – Terry Feb 01 '21 at 00:40