I am doing something like:
struct ABC{
int p,q,r;
};
struct X{
ABC *abc;
X(ABC &abc) : abc(&abc) {}
};
std::vector<ABC> vec;
... //populate vec
X x(vec[2]);
When I debug, x.abc looks correct directly after the assignment but then shortly afterwards the data in x.abc is garbage. It’s making me think the pointer is to a local variable… but vector::operator[] returns a reference so is that possible?
Internally, the
std::vectorusually maintains a dynamic array of the elements it contains. If the vector’s size grows too large and exceeds its old capacity, it allocates a new array, copies the old elements over, then deallocates the old array. As a result, any references or pointers into that old array become invalid and will result in undefined behavior if used.If you want to store a pointer into a vector, you should be sure that the vector does not end up reallocating its internal buffer. You can do this either by waiting until you’ve added all the elements you’re going to add to the vector before taking references, or by calling
vector::reserveto ensure that the capacity is large enough.Even better, though, would be to instead store a reference to the
vectorobject itself along with the index, then look up the element at that index each time. That way, if the vector resizes its internal buffer, your pointers don’t become garbage because you’re re-indexing into the vector each time.Hope this helps!