Assume there is a class A that contains a vector of ints. Now assume that a vector of A's is created. If a reallocation of an A object occurs (so the vector object is moved) due to a push_back for example, will pointers to the ints themselves remain valid? Is this guaranteed?
To clarify:
class A {
public:
A() {};
std::vector<int> a = {1,2,3,4,5,6,7,8,9};
};
int main()
{
std::vector<A> aVec(2);
int *x1 = &(aVec[1].a[2]);
A *x2 = &aVec[1];
std::cout << x1 << " - " << x2 << " - " << aVec.capacity() << "\n";
aVec.resize(30);
int *y1 = &(aVec[1].a[2]);
A *y2 = &aVec[1];
std::cout << y1 << " - " << y2 << " - " << aVec.capacity() << "\n";
}
Running this code gives this:
0x1810088 - 0x1810028 - 2
0x1810088 - 0x18100c8 - 30
so it shows that the pointers remain valid. But I want to make sure that this is guaranteed and not just a chance thing. I'm leaning towards saying that this is guaranteed since the vector's internal data is dynamically allocated, but, again, just wanted to check.
I have looked here [ Iterator invalidation rules ] but it doesn't consider this specific case (i.e. reallocation of the vector object itself).
UPDATE:
I tried this to check what I wrote in the comments for Jarod42's answer:
std::vector<std::vector<int>> aVec(2, {1,2,3});
int *x1 = &(aVec[1][2]);
std::vector<int> *x2 = &aVec[1];
std::cout << x1 << " - " << x2 << " - " << aVec.capacity() << "\n";
aVec.resize(30);
int *y1 = &(aVec[1][2]);
std::vector<int> *y2 = &aVec[1];
std::cout << y1 << " - " << y2 << " - " << aVec.capacity() << "\n";
and got this:
0x16f0098 - 0x16f0048 - 2
0x16f0098 - 0x16f00c8 - 30
which is strange to me. I expected x2==y2.