Jump to content
  • Advertisement
Sign in to follow this  
Waaayoff

Allocating memory with std::vector?

This topic is 2690 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I was wondering, if i want to have a vector of objects, do i write this

std::vector<MyClass*> vec;
vec.push_back(new MyClass());

or

std::vector<MyClass> vec;
vector.push_back(MyClass());

Doesn't vector already store stuff on the heap?

Share this post


Link to post
Share on other sites
Advertisement
vector<MyClass*> is a vector of pointers to MyClass objects.
vector<MyClass> is a vector of MyClass objects.
If you don't need pointers it is probably best to use vector<MyClass>.

Share this post


Link to post
Share on other sites

vector<MyClass*> is a vector of pointers to MyClass objects.
vector<MyClass> is a vector of MyClass objects.
If you don't need pointers it is probably best to use vector<MyClass>.


Yes i realize that, i was just wondering in which cases is a vector of pointers necessary? other than polymorphism perhaps..

Share this post


Link to post
Share on other sites
Vector stores stuff on the heap, yes.

However, by allocating the objects away from the vector you avoid the cost incurred by copying them when the vector is resized or when certain operations are performed (random access erase() calls). Then again, having them densely packed in memory is better for iteration (it suits the processor and the cache to access things this way). Managing allocation yourself means you can guarantee that (smart) pointers to those objects will remain valid regardless of structural modifications to the container.

For polymorphic objects, the answer is obvious. Other than that, the "correct" answer is dependent on a lot of things. The general answer is to use values where possible, and smart pointers (or a smart vector such as boost::ptr_vector<>) otherwise. If doing it the general way doesn't meet your performance requirements, then profile and optimise your bottlenecks.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!