Reputation: 6149
In the following code, I get a different address every time for the first element of std::vector v
. Why is it so?
#include <memory>
#include <iostream>
#include <vector>
int main()
{
std::vector<int> v;
for (int i=0; i<10; ++i)
{
int b = i;
v.push_back(b);
std::cout << std::addressof(v[0]) << std::endl;
}
return 0;
}
Output:
0x603010
0x603030
0x603010
0x603010
0x603050
0x603050
0x603050
0x603050
0x603080
0x603080
Upvotes: 3
Views: 294
Reputation: 1
Right, you don't want to get/use/save the address of an element of a vector (typically unless you don't insert/erase between pointer access and usage, but ideally never, just use the index!). While the vector would maintain contiguous guarantees, it is free to reallocate the elements at larger contiguous memory blocks to accommodate increasing capacity requirements. This isn't, obviously, the case for say a linked list, which doesn't require contiguous memory. And btw, vector iterators face the same "invalidated on insert/delete" concern as pointers to elements.
Upvotes: 0
Reputation: 206647
Because new memory may have to be allocated for the data contained in the vector when you call
v.push_back(b);
P.S.
You said:
In the following code, I get a different address every time for the first element of std::vector v. Why is it so?
If you look at your output, that is not true for every time :)
Upvotes: 8