# c++, is a std::map's value ever copied?

## Recommended Posts

Can I guarantee that once inserted, the value part will not be copied?

// i.e. can i do this:

std::map< int, int > my_map;

int *int_ptr = &my_map::find(5)->second; // assuming 5 exists.

// will int_ptr always be at the same place if I add / remove map entries (not including the int_ptr entry).



And if this is true, is it valid to say an unordered_map will do this as well?

##### Share on other sites
Tispe    1468

Yes. But if the map erases entry 5 then int_ptr will be dangling.

You can use a shared_ptr inside the map, such that if map erases entry 5 then int_ptr will still point to the valid int. Only when the last shared pointer is destoryed the int is automatically deallocated.

std::map<int, std::shared_ptr<int> > my_map;
.
.
.

my_map[5] = std::shared_ptr<int>(new int(SomeValue));

.
.
.

std::map<int, std::shared_ptr<int> >::iterator it = my_map::find(5);

if(it != my_map.end()){
std::shared_ptr<int> int_ptr = (*it).second;
int SomeValue = *int_ptr.get();
}


Edited by Tispe

##### Share on other sites
rip-off    10976

is it valid to say an unordered_map will do this as well?

[url="http://stackoverflow.com/questions/16781886/can-we-store-unordered-maptiterator"]It would seem so[/url].