'What optimizations are enabled by strict aliasing?
Consider this example:
// standard-layout
struct S {
float x;
int y;
};
// not inlineable
void f(float* p); /* {
reinterpret_cast<S*>(p)->y = 43;
} */
int test_f() {
S s{0.0f, 42};
// value of p is "pointer to s.x", s.x and s are pointer-interconvertible,
// so f() could access s.y through p
float *p = &s.x;
f(p);
return s.y; // not 42?
}
void g(int* p);
float test_g() {
S s{0.0f, 42};
// value of p is "pointer to s.y", s.y and s are not pointer-interconvertible,
// so g() can't access s.x through p
int *p = &s.y;
g(p);
return s.x; // always 0.0f
}
Am I correct to assume that f() is allowed access to s.y through &s.x? While test_g() always returns 0.0f, because g() may not access s.x through &s.y.
What if y were std::byte, would the more permissive aliasing preclude this optimization in test_g()?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
