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

Started by
1 comment, last by rip-off 10 years, 5 months ago

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?

Advertisement

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();
}


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

It would seem so.

This topic is closed to new replies.

Advertisement