Why use one vs the other: `boost::shared_array` VS

2019-02-14 14:08发布

问题:

So to deal with large blobs of memory either for an image or similar there are clearly lots of options.

Since I'm a fan of smart pointers and RAII I'm wondering about whether it's smarter to go with :

  • a shared_ptr to a std::vector

or

  • to go with a shared_array pointing to a dynamically allocated array.

What are the conceptual, practical, and performance implications of choosing one vs the other?

回答1:

It's the same as comparing std::vector vs. C array.

Think about shared_array as a RAII C array. What you get is just automatic memory deallocation. Useful in cases when you deal with 3rd-party code that returns arrays. Theoretically it's faster than std::vector in some edge cases, but much less flexible and less secure.

std::vector is probably the better choice.



回答2:

shared_ptr to std::vector

  • + allows amortized constant time push_back
  • - introduces an extra level of indirection over std::vector

shared_array

  • + does not introduce an extra level of indirection
  • - does not allow amortized constant time append, unless you implement it yourself, which again would take an extra level of indirection.