Romain
Romain

Reputation: 1445

C++, Array of objects VS array of pointers pointing to those objects

Consider a c++ class named A. What are the pros/cons to use an array of objects:

std::array<A, 10>

instead of an array of pointers:

std::array<A*, 10>

Upvotes: 0

Views: 4693

Answers (2)

eerorika
eerorika

Reputation: 238351

Here are important differences:

Array of objects:

  • Memory of the objects is managed by std::array.
  • Objects are stored in contiguous memory (good cache efficiency)
  • All objects are of same type
  • All objects exist
  • Assigning an element makes a copy of the object

Array of pointers:

  • Memory of the objects that are pointed to is not managed by the std::array which contains the pointers.
  • You can store pointers to a common base of polymorphic types
  • Pointers can have nullptr value i.e. does not point to any object
  • Assigning an element does not make a copy of the object which is pointed to

Whether any of these things is a pro or a con depends on your use case.

And now for the opinion based part, as a hint to beginners: In my opinion, the fact that the memory is managed by the array makes it clear that the array "owns" the objects. It's often not clear who owns the objects that are pointed to by the pointers. The clarity of ownership, combined with the cache efficiency which is always a bonus, makes the array of objects a good default choice when you are not sure. Use objects in arrays when you can, pointers when you need to. And when you need pointers, consider whether std::unique_ptr is appropriate.

Upvotes: 9

user966379
user966379

Reputation: 2983

if you don't want to use STL array, you can use your own array

1) A array[10]

or

2) A* array[10]

For #1, class A must have a default constructor.

    A needs more memory to hold object

    Whenever you assigned an object to any index of the array, copy constructor gets called

    Compilation time required is more

For #2 There is no need of constructor

   sizeof(array) = size of pointer * 10

   compilation time required is less

   There is no need of default constructor or copy constructor

Upvotes: 0

Related Questions