Search code examples
boostc++14shared-ptr

Can I safely replace boost::shared_array<T> with std::shared_ptr<T[]>?


I'm working on a C++14 codebase which uses boost::shared_array. If I understand correctly, scoped_array and shared_array are the new[]-allocated equivalents of scoped_ptr and shared_ptr, which themselves are mostly deprecated by the availability of std::unique_ptr and std::shared_ptr.

So, can I just use std::shared_ptr<T[]> instead of boost::shared_array<T>?


Solution

  • With C++14: No, you can't.

    Before C++17, std::shared_ptr does not properly work for arrays. But - it does work if you provide a custom deleter; so you can define:

    template <typename T>
    std::shared_ptr<T> make_shared_array(std::size_t n)
    {
        return std::shared_ptr<T> { new T[n], std::default_delete<T[]>{} };
    }
    

    which works (although there may be a potential leak in there if the shared pointer constructor fails).


    With C++17: Yes, you can.

    You can, it seems, safely define:

    template <typename T>
    using shared_array = std::shared_ptr<T[]>;
    

    Related questions: