Why multiple mutable reference even without data access is UB?

As an example, the compiler is permitted to replace taking a mutable reference with loading from the place referred to, all (if any) operations on the dereference of the mutable reference with operations on the loaded value, and the destruction of the mutable reference with a write back to the original place.

This can be an optimization if there's not too much register pressure, because it means that you get to schedule the load very early on, and then operate entirely in registers; however, if it's done to two functions with mutable references to the same place, it converts a previously innocuous looking function into a data race.

3 Likes