0

In general getting the address of a given value in a std::vector<valuetype> isn't safe because if the vector gets reallocated (.resize() or .push_back() expands the size), the addresses of all the objects in the vector may change.

dangerous:

vector<int> vals ;
vals.push_back( 0 ) ;
int *badP = &vals[0];
vals.push_back( 1 ) ;
// badP could be invalid, if 2nd push_back resulted in realloc

I'm wondering about the safety of value types on the right side of a map, however. Is this safe?

dangerous?

map<int,int> vals ;
vals.insert( make_pair(1,1) ) ;
int *p1 = &vals[1];
// is p1 guaranteed to be valid, as long as the vals[1] 
// is not removed, deleted, or changed?

Under what conditions is p1 a bad pointer?

bobobobo
  • 64,917
  • 62
  • 258
  • 363
  • 1
    http://stackoverflow.com/questions/5182122/pointers-to-elements-of-stl-containers So P1 is good unless you call vals.erase(1). – IdeaHat Dec 20 '13 at 19:18

1 Answers1

1

From the doc here:

http://en.cppreference.com/w/cpp/container/map/insert

Inserts element(s) into the container, if the container doesn't already contain an element with an equivalent key.... ....No iterators or references are invalidated

And thinking about how it would be implemented changing on node shouldn't affect any of the others nodes value. The only case you need worry about is if you delete that element from the map.

To handle that case you could have a std::map<int, std::shared_ptr<int>>. And store another shared_ptr then it would be very safe.

EDIT:

However, note that if you are basically try to create a multiple interface container I can strongly recommend the Boost.MuliIndex library.

http://www.boost.org/doc/libs/1_55_0/libs/multi_index/doc/index.html

Community
  • 1
  • 1
111111
  • 15,686
  • 6
  • 47
  • 62