[Solved] The rationale for ownership semantics seem unusual to me


#1

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 of y 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?


#2

The key here is that y is &x[0], not just &x. By using the [0] indexing syntax, y is set to a reference to the first element of the vector. y doesn’t know about the fact that x is a Vec at all, it’s literally just a pointer to where the first item of x is in memory.

This is safe because rust prevents modifying x at all while any references to elements within it exist. The ownership system is there to prevent y from becoming a dangling pointer, which might be possible if x could be mutated while y exists.


#3

Ah, so I completely misread the code snippet. I thought y referred to the vector, not the first element in it.