1

image of the code and description

if the reference is a new place in memory does it contain the reference of the object it is bounded to

walnut
  • 21,629
  • 4
  • 23
  • 59
Mabouelail
  • 31
  • 5

4 Answers4

4

It depends on how smart your compiler is, and on its optimization settings.

In the worst case, a reference is usually implemented as a pointer.
In the best case, it's completely optimized away and doesn't require any storage.

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
2

The C++ standard does not specify how references are implemented, just their behaviour. (For example a pointer to a reference to an object compares true with a pointer to an object.)

Early C++ compilers implemented them pretty much in the same way as pointers, but later compilers employ different strategies, including compiling out references altogether.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
2

Yes and yes. This really depends on context (where it is being used), what optimizations are on, and even the compiler.

See https://godbolt.org/z/bPuBxg

In the unoptimized version, with g++, you can see that the memory address is loaded into a register, then saved into a new spot in memory. So the reference does take up space. In the optimized version, the reference is compiled out.

ChrisMM
  • 8,448
  • 13
  • 29
  • 48
2

refernces are variables that will always point to the address of the object they are bound to.

In C++, it's unclear if they are actually implemented to hold two separate addresses. However, it is the intention of the language that you should believe that they share the same place in memory.

int a = 5;
int &b = a;
cout << "a: " << &a << '\n';
cout << "b: " << &b << '\n';
----------
a: 0x29fef8
b: 0x29fef8