Pointer to object in std::vector

Hello,

I store and access an object in a std::vector as follows:
1
2
3
4
//vector is a member variable
vector.push_back(MyObject());
//storing the pointer to the object in the vector
storePointer(&vector.at(0));

Will the pointer always (as long as I don't remove the object) be valid? Even if I add/remove other objects?

Thanks!
No. Adding objects may cause the vector to re-allocate its memory.

And here's proof:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <vector>

int main()
{
    std::vector<int> vi;

    for (int i=1; i <= 10; ++i)
    {
        vi.push_back(i);
        std::clog << &vi.at(0) << '\n';
    }

    std::clog << std::endl;
}
0x550ec8
0x550ee8
0x550ef8
0x550ef8
0x550f10
0x550f10
0x550f10
0x550f10
0x550f38
0x550f38
Thanks for the quick reply!
Check out section Iterator validity in http://www.cplusplus.com/reference/vector/vector/push_back/ and in other standard container (e.g. std::vector) methods.
As a side, my_vector.data() returns the pointer also. No need for &my_vector.at(0)
Topic archived. No new replies allowed.