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

Can you allocate an array with something equivalent to make_shared?


buffer = new char[64];
buffer = std::make_shared<char>(char[64]); ???

Can you allocate memory to an array using make_shared<>()?

I could do: buffer = std::make_shared<char>( new char[64] );

But that still involves calling new, it's to my understanding make_shared is safer and more efficient.


Solution

  • The point of make_shared is to incorporate the managed object into the control block of the shared pointer,

    Since you're dealing with C++11, perhaps using a C++11 array would satisfy your goals?

    #include <memory>
    #include <array>
    int main()
    {
        auto buffer = std::make_shared<std::array<char, 64>>();
    }
    

    Note that you can't use a shared pointer the same way as a pointer you'd get from new[], because std::shared_ptr (unlike std::unique_ptr, for example) does not provide operator[]. You'd have to dereference it: (*buffer)[n] = 'a';