0ctoDragon
0ctoDragon

Reputation: 541

Why do pointers to variables in a vector stay valid?

Take this code for example:

int a = 1;
int b = 2;
int c = 3;
std::vector<int> myVector;
myVector.push_back(a);
myVector.push_back(b);
myVector.push_back(c);
int * b_pointer;
b_pointer = &myVector[1]

In my experience b_pointer will alway point to b even though the vector may reallocate which should make it so b_pointer points to junk data. Is there ever a situation in which this wont work?

Upvotes: 0

Views: 100

Answers (2)

After a reallocation of myVector's internal buffer happens, b_pointer will point to invalid memory, plain and simple. Dereferencing it will result in Undefined Behaviour.

However, it's very possible that the memory to which it points still contains the data which it held previously; why would some pay the cost of trashing it somehow? Nobody's legally able to access it anyway. If sufficient allocations happen in the meantime, it will eventually get overridden by something else.

Upvotes: 0

Salgar
Salgar

Reputation: 7775

You are essentially asking whether an iterator stays valid (Although, the type of a vector iterator is not necessarily the same as a simple pointer)

The documentation for std::vector<>::insert says

If a reallocation happens, all iterators, pointers and references related to the container are invalidated. Otherwise, only those pointing to position and beyond are invalidated, with all iterators, pointers and references to elements before position guaranteed to keep referring to the same elements they were referring to before the call.

The thing you are probably noticing is that when a realloc happens, it sometimes just extends the current allocation if there is space available.

Upvotes: 4

Related Questions