Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using class objects in std::vector

Tags:

c++

std

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?

like image 620
Pavel Oganesyan Avatar asked Feb 19 '26 03:02

Pavel Oganesyan


2 Answers

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.

like image 198
Rost Avatar answered Feb 21 '26 17:02

Rost


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.

like image 37
Olaf Dietsche Avatar answered Feb 21 '26 17:02

Olaf Dietsche