Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ – Pointer stability of returning an element from std::vector<T*>?

What does std::vector look like in memory?

So I was reading the above just now and I noticed the following quote:

Iterator and address stability of elements is guaranteed with std::vector only if no reallocation takes place

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So let’s say I have an std::vector<> member of generic type T* (T representing anything). The member itself is a pointer to the first element in the std::vector<> since the heap-allocated buffer is contiguous in memory and an iterator just shifts along by sizeof(T) bytes for each element’s pointer in the std::vector<>.

In an std::vector<> of generic type T*, each element’s pointer is just a pointer to a pointer, to my understanding at least. Be that as it may, this means that the above address stability only applies to the element pointer and not the pointer at the element too, right?

>Solution :

Yes, that’s correct. The items pointed at by the vector do not have to change and therefore your other resources are safe to rely on the values. The memory location of the pointers of the vector will change though, because that’s what reallocation does.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading