Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::shared_ptr<T[]> VS std::array<T, size>/std::vector<T>

So, I have a question, the answer to which I could not find. In C++ shared pointer has a constructor that can contain a raw array(std::shared_ptr<int[]>,for example.)

What are the benefits of using it compared to std::array or std::vector?

Tried to search, ask gpt. As for std::vector, there is a suggestion that memory allocation can be avoided with std::shared_ptr, but that doesn't explain why using this when there is a std::array

like image 871
Maksim Kononykhin Avatar asked Apr 14 '26 02:04

Maksim Kononykhin


1 Answers

Unlike all other listed options, std::array requires the size to be known at compile-time, and doesn't store the elements on the heap (unless it itself is on the heap).

std::vector<T> can work with a size not known at compile-time, and should be your default choice in that case. It always stores the elements on the heap.

std::unique_ptr<T[]> can be thought of as a stripped down std::vector. It doesn't know its size, which saves a tiny bit of memory (sizeof(std::unique_ptr<T[]>) is normally sizeof(void *), while sizeof(std::vector<T>) is normally 3 * sizeof(void *)).

Because it doesn't store its size, there's very few things it can do out of the box: it can't be copied (only moved), it can't insert or remove elements, etc. You can do all of this manually if you store the size separately, but then it's just std::vector with extra steps.

std::shared_ptr<T[]> adds an extra feature to std::unique_ptr<T[]> - shared ownership, like any other std::shared_ptr<??>.

like image 56
HolyBlackCat Avatar answered Apr 16 '26 15:04

HolyBlackCat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!