Search code examples
c++11shared-ptrmake-shared

How to use make_shared to create an array of objects of the same type?


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?


Solution

  • 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.