Reputation: 1445
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
Reputation: 238351
Here are important differences:
Array of objects:
std::array
.Array of pointers:
std::array
which contains the pointers.nullptr
value i.e. does not point to any objectWhether 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
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