Sign in to follow this  
bradbobak

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

Recommended Posts

bradbobak    1825

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