Advertisement Jump to content
Sign in to follow this  
bradbobak

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

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

 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 this post


Link to post
Share on other sites
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();
}

Edited by Tispe

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!