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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
std::vector<MyClass>shall be preferable in most cases. Yes, it will store objects in heap (dynamic storage) by defaultstd::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::vectorof pointers will require you to destroy objects manually, e.g. callingdeletefor 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.