0

Possible Duplicate:
How is reference implemented internally?

void f (int& a)
{
    a ++;
}

int main ()
{
    int b = 5;
    f(b);
    cout << b << endl; //prints 6
}

When I saw the syntax for references in C++, it initially looked like the variable b (if it were an object) would be copied into f. How do these references actually work under the hood? (Some simple asm would be great.)

Community
  • 1
  • 1
corazza
  • 31,222
  • 37
  • 115
  • 186
  • 1
    References are simply aliases to the original variable.Any modification on a reference will modify the variable being referred.There is no copying involved.The exact detail of how references are implemented is **Unspecified** by the standard.Having said that under the hood most compilers simply use pointers for implementing references. – Alok Save Sep 18 '12 at 09:01
  • Your compiler will give you sample asm -- find the options for outputting unassembled code or the tools for disassembling its binary output. – Steve Jessop Sep 18 '12 at 09:22

2 Answers2

3

In this case, the pass-by-reference most likely uses pointer semantics - i.e. the address of the object is probably passed as the parameter.\

When I saw the syntax for references in C++, it initially looked like the variable b (if it were an object) would be copied into f.

Nope. That's one of the upsides of references - no copying.

    f(b);
00DF1405  lea         eax,[b]  
00DF1408  push        eax  
00DF1409  call        f (0DF1177h)  
00DF140E  add         esp,4  

eax will contain the address of b, and is then pushed onto the function argument stack.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
2

Under the hood in C++ references implemented exactly like pointers. The only difference is some compile time checks and different syntax. So in your case function f gets a "pointer" to integer b and increments the value of b.

Gurthar
  • 23
  • 3