Search code examples
c++vectordangling-pointer

When an std::vector grows are addresses to elements within it no longer valid?


Suppose I have the following:

struct Foo {
Foo () : bar(NULL), box(true) {}
Bar* bar;
bool box;
};

and I declare the following:

std::vector<Foo> vec(3);

I have a function right now which does something like this:

Foo& giveFoo() { //finds a certain foo and does return vec[i]; }

Then the caller passes along the address of the Foo it obtains by reference as a Foo* to some other guy. What I'm wondering, however, is if this pointer to Foo will remain valid after a vector grow is triggered in vec? If the existing Foo elements in vec are copied over then presumably the Foo* that was floating around will now be dangling? Is this the case or not? I'm debugging an application but cannot reproduce this.


Solution

  • Any pointers or references to elements will be invalidated when the vector is reallocated, just like any iterators are.