0

As far as I understand (see this post), C++ references implementation is based on pointers. However, I wonder how the mechanism work when no actual variable is passed, but a literal constant. Let me illustrate what I mean with an example:

#include <iostream>

void f(const int& n)
{
  std::cout << n << std::endl;
}

int main()
{
  f(42);
}

What I'm passing to the f() function is literal 42. The caller is not using any actual variable.

Maybe a "shadowed" on-the-fly variable and associated pointer is used in this case? Anybody can confirm (or explain the actual mechanism if I'm wrong)?

As reference, in the case the answer would be compiler-dependant, we typically use gcc 4.4 (in CentOS 6.x) and gcc 4.9 (in Debian 8).

Note: I already know that it is not a good idea to pass by reference a constant integer. I mean, a better approach fo the f() function above will be pass-by-value with void f(int n). However I think is a good example to illustrate what my doubt.

fgalan
  • 11,732
  • 9
  • 46
  • 89
  • 3
    You can always look at the generated code to see what the compiler does. – Some programmer dude May 29 '17 at 09:40
  • 2
    *"C++ references implementation is based on pointers"* - None of that is specified, and implemented at the discretion of the compiler. A compiler can choose any implementation it sees fit, including not passing anything at all, if it can prove that it needn't. – IInspectable May 29 '17 at 10:23
  • You are right @IInspectable. That statement was a rough summary of some of the answer in the https://stackoverflow.com/questions/2936805/how-do-c-compilers-actually-pass-reference-parameters post. Thanks for the feedback! – fgalan May 29 '17 at 10:50

2 Answers2

2

Each compiler gets to decide how they implement literals (and references for that matter). I'm not intimately familiar with how is implemented gcc, but I can conjecture a possible implementation:

Literal values are stored in a read-only section of the executable binary, which is loaded into memory at the start of the execution. Since the object is in memory, it has an address. That address can be assigned to a pointer / reference.

I wonder how the mechanism work when no actual variable is passed

Objects can exist without a variable. Consider for example dynamic allocation. Those objects can be pointed / referred to. Whether there is a variable or not has little effect on how references work.

eerorika
  • 232,697
  • 12
  • 197
  • 326
1

A literal is allocated in memory, it is static memory, but still memory. Assuming 42 is a 4 Bytes integer, it will be represented in memory as

->| 00000000 | 00000000 | 00000000 | 00101010 |

The memory reference what C++ is using (const int& n) is pointing to that memory address (you can imagine memory as table with cells).

Since your are using little endian system, the actual memory representation should be:

->| 00101010 | 00000000 | 00000000 | 00000000 |
carlosvin
  • 979
  • 9
  • 22