11
Consider the following class:
struct Type {
int a, b, c;
int& ref;
Type(int m) : a(m), b(m), c(m), ref(a) { }
Type(const Type& ot) : a(ot.a), b(ot.b), c(ot.c), ref(a) { }
} obj;
Here we have that the sizeof(Type)
is 24
. However obj.ref
can always and in any situation/context be replaced by obj.a
, so that the reference can be resolved at compile time and make worthless store the 8 bytes of the reference in the object (and the 4 padding). Ideally the sizeof(Type)
can be 12
(only the three int
s).
A compiler can perform this optimization while strictly following the rules of the standard? Why? Is there any situation where this optimization would be incorrect?
Demonstrate with an example that produces different behavior with/without optimization.
I believe that this type of optimization is not allowed, because it moves the layout of the struct/class. But I have to search to give an answer with certainty.
– C. E. Gesser
I think the same. But, I cannot find any case where this becomes a problem or incompatibility. Note: None of the compilers I have tested do this (obviously).
– Guilherme Bernal