Reputation: 6924
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?
Upvotes: 2
Views: 2091
Reputation: 9089
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.
Upvotes: 6
Reputation: 15673
std::vector<MyClass>
will store objects on the heap (probably), std::vector<MyClass*>
will store your pointers on the heap (probably) and your objects wherever they were created. Use std::vector<MyClass>
whenever applicable, if you need to support inheritance std::vector<std::unique_ptr<MyClass>>
again when applicable. If your vector isn't supposed to own the objects an std::vector<MyClass*>
can be useful, but that's rarely the case.
Upvotes: 0
Reputation: 20457
Depends. Storing copies of your class in the container is easier to work with, of course, but you need to run the copy constructor every time to save an instance to the container which may be problematical. Also, your container cannot store anything but that one class - in particular it cannot store other classes that are specialised ( inherited ) from your base class. So, in general, you usually end up having to store pointers to the class.
There are snags with storing pointers. However, to get the best of both worlds, consider using boost::ptr_vector instead, which has the advantages of smart pointers without the overhead.
Upvotes: 0
Reputation: 74018
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.
Upvotes: 4