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?