0

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.

6
  • 1
    They don't have the same address as the original. They refer to the original. By your reasoning, two pointers to the same address shouldn't occupy two pointer's worth of memory? Commented Nov 16, 2013 at 7:40
  • One of the answer for this question (stackoverflow.com/questions/57483/…) states "A pointer has its own memory address and size on the stack (4 bytes on x86), whereas a reference shares the same memory address (with the original variable) but also takes up some space on the stack" Commented Nov 16, 2013 at 7:43
  • That part of the answer only refers to pointers/references "on the stack". References "on the stack" might not need storage at all (they might not "exist" at all in the generated code) if something else already refers to that object in the "same scope". Commented Nov 16, 2013 at 7:52
  • @Shubham That is right. The reference is just an alias for a variable, so the address-of operator has to return the address of that variable. What adds some confusion is that they are typically implemented with pointers under the hood. But one should not think of the reference as a separate entity to the thing it refers to. Commented Nov 16, 2013 at 7:53
  • "so the address-of operator has to return the address of that variable" @juanchopanza Sorr, I kind of not understood what you explained. Can you give an example? Commented Nov 16, 2013 at 19:09

2 Answers 2

3

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).

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.