简体   繁体   中英

What does taking address of return from std::vector::operator[] do?

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::vector usually 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::reserve to ensure that the capacity is large enough.

Even better, though, would be to instead store a reference to the vector object 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM