Shubham
Shubham

Reputation: 172

How Reference in C++ Works? Why do they need memory?

References as they say have same address as original variable then why do they consume memory. Refer this post Reference in place of getters? in this example if I have reference as a class member the size of class increase.

Edit 1

Here is the output I get on VS 2010 Express

The program:

class X
{
    int i;
    int &I;
public:
    X():I(i){}
}x;

class Y
{
    int i;
public:
    Y(){}
}y;

int main()
{
    int j =0;
    int &J = j;

    return 0;
}

Watch Window: Watch Window

Disassembly:

int main()
{
01101390  push        ebp  
01101391  mov         ebp,esp  
01101393  sub         esp,0D8h  
01101399  push        ebx  
0110139A  push        esi  
0110139B  push        edi  
0110139C  lea         edi,[ebp-0D8h]  
011013A2  mov         ecx,36h  
011013A7  mov         eax,0CCCCCCCCh  
011013AC  rep stos    dword ptr es:[edi]  
    int j =0;
011013AE  mov         dword ptr [j],0  
    int &J = j;
011013B5  lea         eax,[j]  
011013B8  mov         dword ptr [J],eax  

    return 0;
011013BB  xor         eax,eax  
}

It looks like this is implemented as exactly as a pointer in VS at least.

Upvotes: 0

Views: 103

Answers (2)

Michael Burr
Michael Burr

Reputation: 340316

References are typically implemented using pointers. However note that the standard specifically says (C++11 8.3.2/4 - "References"):

It is unspecified whether or not a reference requires storage (3.7).

Upvotes: 3

Elliott Frisch
Elliott Frisch

Reputation: 201487

It takes space to store the reference itself. The same size as a pointer in fact.

Upvotes: 1

Related Questions