Hello, I'm an experienced C++ programmer and I'm trying to learn Rust. I'm reading through the intro and something is very unsettling to me:
In this specific case, when we create the vector, we may have only allocated space for two elements. Adding a third would mean allocating a new chunk of memory for all those elements, copying the old values over, and updating the internal pointer to that memory. That all works just fine. The problem is that
y
wouldn’t get updated, and so we’d have a ‘dangling pointer’. That’s bad. Any use ofy
would be an error in this case, and so the compiler has caught this for us.
This is incredibly scary to me - I thought that y
referenced the vector, not the internal pointer held within the vector. How could it even be possible for a dangling pointer to be created from a reallocation if that is all handled internally by the vector?