2

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
  • 1
    Here you're initializing a class member inside the class definition. This means that in each constructor the code to initialize that field will be executed. Now the class itself is still a class containing an int and an int& reguardless 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. Commented May 27, 2021 at 9:18

1 Answer 1

3
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.

Sign up to request clarification or add additional context in comments.

1 Comment

All constructors for this class are private, so aggregate initialization is not available for this class. I tried using an aggregate initializer and it does not compile: int y;withref fullref{1,y};

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.