Jump to content

  • Log In with Google      Sign In   
  • Create Account


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


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
2 replies to this topic

#1 bradbobak   Members   -  Reputation: 1019

Like
0Likes
Like

Posted 01 November 2013 - 12:05 AM

 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?

 



Sponsor:

#2 Tispe   Members   -  Reputation: 978

Like
3Likes
Like

Posted 01 November 2013 - 12:59 AM

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, 01 November 2013 - 01:13 AM.


#3 rip-off   Moderators   -  Reputation: 7651

Like
1Likes
Like

Posted 01 November 2013 - 04:46 AM


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

It would seem so.






Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS