Current state of in-place initialization
Current state of in-place initialization
Posted Oct 11, 2026 6:40 UTC (Sun) by matthias (subscriber, #94967)In reply to: Current state of in-place initialization by donald.buczek
Parent article: An update on Rust's project goals
We are talking about types that are not allowed to be moved. So the code might be unsound (contain UB) before this optimization. So this optimization has to be performed before any other optimization that might trigger this UB. This optimization would also need to be applied in debug mode where optimizations are turned off.
This might sound plausible. But the biggest issue is: Why do we need in-place initialization in the first place? Usually for self-referential types. So the initialization code will at some point take the address of the struct and write it into the struct. In the unoptimized code this initialization happend before the move. So it is not only necessary to optimize the move, but we must also make sure that the optimized code never sees the address the struct has on the stack. By some compiler magic it would need to initialize the struct with the address that it will get on the heap (or wherever it will end up), from some allocation that might happen after the initialization in program order. And the compiler cannot simply reorder initialization and allocation, as the memory allocator surely involves some memory barriers.
I have to admit that I have no expertise in compiler development. But I am quite sure that you do not want to rely on compiler optimizations to remove UB from your code. The unoptimized code should never have UB in the first place.
