Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

vector

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?

like image 691
Anne Quinn Avatar asked Dec 07 '25 04:12

Anne Quinn


1 Answers

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.

like image 78
NathanOliver Avatar answered Dec 08 '25 17:12

NathanOliver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!