Reputation: 2670
Let us say I create std::vector<int*> myVec;
and reserve 100 entries and populate the vector with values so that all 100 elements have valid pointers. I then cache a pointer to one of the elements,
int * x = myVec[60];
Then, if I append another int *
which triggers a resize along with a move due to heap fragmentation, does the previous pointer to a pointer become invalidated or does it point to the new location in memory?
If my memory servers me correct, if the example were to std::vector<int> myVecTwo
with the same conditions as above and I stored a ptr like
int * x = &myVecTwo[60];
and proceeded to append and resize, that pointer would be invalided.
So, my question is as follows. Would the pointer to the pointer become invalidated? I am no longer certain because of the new C++ std functionality of is_trivially_copyable and whether the std::vector makes use of such functionality or POD checks.
Would the pointer by invalidated in C++11?
Upvotes: 3
Views: 246
Reputation: 172964
No.
As you showed, after the reallocation, the pointers to the elements of the vector
, like int * x = &myVecTwo[60];
would be invalidated. After the reallocation, the elements themselves would be copied, but the object pointed by the element pointers won't be affected, then for int * x = myVec[60];
, after the reallocation x
is still pointing to the same object, which has nothing to do with the reallocation of the vector
.
Upvotes: 5