Search code examples
c++boostc++11shared-ptr

Is there a difference between those ways to store an array of pointers?


I guess all the solutions below are equivalent (part from 4) but is it only a matter of preference?

Object* myArray[10];                             // 1. C-style
std::array<Object*, 10> myArray;                 // 2. C++11
boost::ptr_array<Object, 10>myArray;             // 3. Boost
std::array<std::unique_ptr<Object>, 10> myArray; // 4. taking ownership of the pointer

Why isn't there a class in Boost doing what line 4 is doing in a ptr_array-like way? Is it because generally there isn't a good reason to store an array of pointers if the class containing it is taking ownership and destroys the objects when necessary?

The alternative that I can see to line 4 would be to have an array of objects instead of pointers of objects: std::array<Object, 10> myArray.

Edit: Removed the "best-way" thing in the question as it wasn't really relevant.


Solution

  • In programming there is no such thing as "best way" that is independent of goals.

    All the variants have their pros&cons, and you evaluate them against what you want to do. Drop the hopeless ones and pick some of the remaining.