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?
intand anint®uardless of how you initialize it (you could move that field initializtion in a constructor explicitly in another .cpp file). If a translation unit sees that class it will only know what its fields are, not that all of its construcors behave in a certain way.