Search code examples
c++structreferenceinitializationlanguage-lawyer

Is it a missed optimization, when a compile-time known reference takes space in a struct?


See this example:

struct Foo {
    int a;
    int &b = a;
};

Is it a missed optimization, if sizeof(Foo)!=sizeof(int)?

I mean, can the compiler remove b from the struct, as it always refers to a?

Is there anything which stops the compiler to make this transformation?

(Note, struct Foo looks as it is. No constructors, etc. But you can add anything around Foo, which shows that this optimization would violate the standard)


Solution

  • No, because you can use aggregate initialization of a variable to have it refer to something else.

    struct Foo {
        int a;
        int &b = a;
    };
    
    int c;
    Foo f{7, c};