1

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

1 Answer 1

2

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:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.