Is it possible to define a class in which reference variables occupy no extra storage?

Viewed 57

C++ has the option not to allocate storage for a reference variable if the referenced object is known at compile time. Other questions here have noted that a reference to a constant occupies no storage.

Why then does C++ not perform the obvious optimization of not allocating storage for the reference variable in the following case? rg can only reference glob, so why is it necessary to allocate storage for a pointer?


struct nowtref 
{
    int x;
};

int glob;

class withref
{
    int x;
    int& rg{glob};
};

int main(int argc, char* argv[])
{
    printf("sizeof(withref) = %lu\n", sizeof(withref));
    printf("sizeof(nowtref) = %lu\n", sizeof(nowtref));
}

When run, this program prints:

sizeof(withref) = 16
sizeof(nowtref) = 4

Is it possible to have a reference inside a class which does not occupy storage?

1 Answers
int& rg{glob};

This defines only the default value for this reference. Using aggregate initialization it is possible to initialize this reference to refer to some other object. As such, this reference cannot be (simply) optimized away.

Related