Home > Net >  Are addresses into constant vectors, inside a non-constant vector, stable?
Are addresses into constant vectors, inside a non-constant vector, stable?

Time:09-23

If I have a std::vector<std::vector<char>>

Where the following is true:

  • The inner vectors's size is never changed
  • The outer vector's size is changed with insertions and removals

Can I take an address into the inner vector like this, use it after modifying the outer vector, and be safe?

std::vector<std::vector<char>> buffer;

#include <code that inserts into "buffer" uhhh 10 vectors with 100 char each>

char * ch = buffer[5].data();

// example of code that never erases/resizes the vector "ch" is pointing into...
// ... BUT will remove/insert vectors around it, prompting "buffer" to reallocate
buffer.erase(buffer.begin(), buffer.begin()   4); 
buffer.shrink_to_fit();
buffer.insert(buffer.begin(), std::vector<char>(1)); 

assert(buffer[1].data() == ch);    // the 5th inner-vector moved to index 1
printf("how is this bit%c?", *ch); // but hopefully "ch" is still valid?

CodePudding user response:

If the outer vector has to grow, it will allocate a new buffer and move all of the inner vectors into that buffer. That means the addresses of those inner vectors will change but that does not mean the addresses of the buffers of the inner vectors will change. They will stay the same as vector is required to not invalidate any iterators/references/pointers to elements in the vector when it is moved.

  • Related