Jump to content
Site Stability Read more... ×
  • Advertisement
Sign in to follow this  

C++ STL map - Does memory get reallocated when inserting?

This topic is 2935 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

Hello everyone,

After searching, I've found plenty of hints but no definite answer to my question - if I insert into a STL map, will memory ever be reallocated, or is the address of any inserted object fixed?

I've tried testing it, and I've not found anything that refutes this, but it could be just that I have performed the tests properly.

Maybe I should explain what I'm trying to do rather than just ask a specific question, as there's probably a better way of doing this anyway.

I have three maps which I'm using as sparse arrays, and the key for each is just an unsigned int, vis:

map<unsigned int, Fruit> Fruits
map<unsigned int, Seed> Seeds
map<unsigned int, Recipe> Recipes

These are just used to contain my objects, and all the insertions are done as part of programme initialisation, and then they are left alone until destruction. Importantly, they are used to contain ALL instances of these objects in the program.

The complication comes because each of the classes Fruit, Seed and Recipe classes needs a way of accessing an instance of the other two classes. I felt that rather than just giving them the key number and then passing the whole map by reference, it would be neater to use a pointer, which is obtained during initialisation, eg:

pFruit = &Fruits[45];

I liked this approach as even if Fruits[45] hadn't been created yet, the map itself would construct a new Fruit object and return its address. Later on in initialisation, the object will usually be altered, but if not it wouldn't matter as Fruits[45] would still have been constructed.

Which brings me to my problem - the address is only obtained once, during initialisation. So will the address given by &Fruits[45] always be valid, even if the initialisation inserts a few hundred other Fruit objects into the map AFTER - or is there a much neater way of achieving all this anyway?

Share this post

Link to post
Share on other sites
Pointers or iterators to map elements will only be invalidated when that element is deleted. Any other insertions into the map won't move the elements around.

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.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!