Matt Godbolt's blog
15 hours ago
- Aliasing prevents compiler optimizations, and understanding why is crucial.
- A counter class example shows that with `int` types, the compiler updates the member variable each loop iteration due to potential aliasing, while with `long` types, it caches the accumulator in a register because strict aliasing rules prevent overlap.
- C++ strict aliasing allows the compiler to assume non-overlapping memory for different types, enabling optimizations like register caching and vectorization.
- Fixes include using a local variable for accumulation (e.g., `std::accumulate`) or the non-standard `__restrict` keyword.
- Aliasing is a common pitfall in C++, especially with base types; detecting unexpected memory writes in hot loops can reveal it.