What is better -
std::vector<MyClass*>
or
std::vector<MyClass>
? I mean, will the second option store objects in heap anyway? Which one is faster and cleaner?
std::vector<MyClass> shall be preferable in most cases. Yes, it will store objects in heap (dynamic storage) by default std::allocator.
The advantages are that objects are automatically destroyed on vector destruction and are allocated in single contiguous memory block reducing heap fragmentation. So this way it's cleaner.
Also this way is faster because it could minimize memory allocation operations. Vector will preallocate storage before constructing objects, so for N objects it will be M allocation operations and N constructor call, N > M (the bigger is N - the greater is difference). If you create objects manually and place them to vector by pointers it will lead to M allocations and N constructions, M = N + X, where X is vector storage allocations. And you always can minimize vector memory allocations if you know number of stored objects - using std::vector::reserve().
On the contrary using std::vector of pointers will require you to destroy objects manually, e.g. calling delete for dynamically allocated objects. This is not recommended. Such containers shall be used only as non-owning. Objects ownership shall be maintained externally in this case.
Yes, the second version will store the objects on the heap too, but in a more compact form, namely an array of MyClass.
In the first form you must allocate and deallocate your objects, while std::vector will do this for you in the second version.
So, as always, it depends on your needs and requirements. If you can choose, take the second form:
std::vector<MyClass>
it's much easier to maintain.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With