Xavier
Xavier

Reputation: 9049

Is the address of the first element of a vector fixed?

For example if I do something like this:

vector<int> myvector;
myvector.push_back(100);
int * ptr = &(myvector[0]);
myvector.clear();
myvector.push_back(10);

Will ptr still be valid? Or could it now be pointing to garbage?

Upvotes: 1

Views: 422

Answers (2)

fredoverflow
fredoverflow

Reputation: 263210

23.2.3 §4 says:

a.clear() [...] invalidates all references, pointers, and iterators referring to the elements of a and may invalidate the past-the-end iterator.

Since there is no such thing as "un-invalidation", using ptr after clear results in undefined behavior.

On a side note, the parenthesis in &(myvector[0]) are not needed. Postfix operators always have higher precedence than prefix operators in C++, so writing &myvector[0] is just fine.

Upvotes: 7

smparkes
smparkes

Reputation: 14073

It could be pointing to garbage. vector reallocates memory as needed when an instance grows or shrinks so you can't rely on the address not changing. That's why the types used for vector have to obey STL-compatible constraints like copy-ability. That's also why auto_ptr isn't safe in STL containers.

Upvotes: 3

Related Questions