2

We could use "make_shared" to create an object faster and safer compared to use "new". For example,

shared_ptr<Dog> p = make_shared<Dog>("Luther"). 

If I need to create an array of objects (e.g. Dog[3]), is it possible to use "make_shared" instead "new"? Besides, is it possible to use a customized delete function with make_shared method?

Linda
  • 37
  • 5
  • If you do not need the _shared_ ownership, `std::vector` may suffice. In C++20 `make_shared` can be used with `Dog[]`. I would think a bit harder to eliminate the need for shared ownership at all by structuring my object ownership to have hierarchic lifetimes. – Maxim Egorushkin Dec 30 '18 at 19:37
  • 1
    according to [cppreference](https://en.cppreference.com/w/cpp/memory/shared_ptr/make_shared), that's getting addded in c++20 (#4) –  Dec 30 '18 at 19:53

1 Answers1

0
auto parr = make_shared<std::array<Dog, 3>>(std::array<Dog, 3>{"Bob", "Charlie", "Alice"});

If you want a shared pointer to the nth element...

auto pelem = std::shared_ptr<Dog*>{p, p->data()+n};

which does 0 allocations.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524