0

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>?

einpoklum
  • 118,144
  • 57
  • 340
  • 684

1 Answers1

1

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


When you use C++17 or later - you can, it seems, safely define:

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

Related questions:

einpoklum
  • 118,144
  • 57
  • 340
  • 684