I'm new to the idea of reference in C++, I have a question concerning the memory allocation of reference to a pure number constant. (Another thing I want to check first is that I suspect const reference, which I frequently came across, means reference to const, but I'm not sure.)
Here is my testing on ideone.com:
#include <stdio.h>
int main() {
const int r0 = 123;
const int &r1 = 123;
const int &r2 = 123;
const int &r3 = r2;
printf("%p\n", (void *)&r0);
printf("%p\n", (void *)&r1);
printf("%p\n", (void *)&r2);
printf("%p\n", (void *)&r3);
return 0;
}
and the result:
0x7ffee3bd74c4
0x7ffee3bd74c8
0x7ffee3bd74cc
0x7ffee3bd74cc
The reason r2 is the same as r3 is clear from this answer - How does a C++ reference look, memory-wise?, which says it's depending on compiler. But I'm thinking about why compiler doesn't also make r0,r1,r2 all the same, since all have the same pure constant value 123. (or called prvalue if no wrong search)
As a note: After some search on this site, I found a most related question - but in python. Although different language but I thought the idea should be the same/similar: from the link, if my program were written in python then there will be only one 123 is in the memory space for saving space.
Some other answers I've read:
- C++ do references occupy memory: This answer suggests that if it's necessary then
int &xis implemented as*(pointer_to_x). - How does a C++ reference look, memory-wise?: This answer suggests that compiler will try its best to save space.