Why references to the same constant take distinct memory space in C++?

  • A+

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:

  1. C++ do references occupy memory: This answer suggests that if it's necessary then int &x is implemented as *(pointer_to_x).
  2. How does a C++ reference look, memory-wise?: This answer suggests that compiler will try its best to save space.


Your 123 isn't a "constant". Rather, it is a literal. A literal forms an expression that is a prvalue (i.e. a temporary object initialized with the value of given by the literal). When you bind that expression to are reference, the lifetime of that object is extended to that of the reference, but the important point here is that each such object is a distinct object, and thus has a distinct address.

If you will, the text string "123" provides a rule for how to create objects, but it is not by itself an object. You can rewrite your code to make this more explicit:

const int & r = int(123);   // temporary of type "int" and value "123" 

(There's no single such thing as "a constant" in C++. There are lots of things that are constant in one way or another, but they all need more detailed consideration.)


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: