Sign in to follow this  
RonnieCassinello

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

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:

[code]
map<unsigned int, Fruit> Fruits
map<unsigned int, Seed> Seeds
map<unsigned int, Recipe> Recipes
[/code]

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:

[code]
pFruit = &Fruits[45];
[/code]

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this