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?