简体   繁体   中英

How do C++ compilers actually pass literal constant in reference parameters?

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.

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.

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 |

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM