Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where does the reference variable gets stored [duplicate]

Tags:

c++

memory

I know that reference does not take any memory it will point to the same memory location which it is referencing. for eg

int i=10;
int &r = a;

suppose i points to the memory location 1000 so in this case r will also point to the memory location 1000. But in C++ whenever we are declaring a variable it will get stored in the memory at some location. In this case r is pointing to some location but it should be stored somewhere in memory via some internal representation. thanks in advance.

like image 723
Sandeep Sharma Avatar asked Jun 09 '16 07:06

Sandeep Sharma


People also ask

Where are reference variables stored?

Reference is one type of variable stored on stack because of there is need to perform operation on them where object stored on heap.

Are reference variables stored in stack or heap?

Whenever an object is created, it's always stored in the Heap space and stack memory contains the reference to it. Stack memory only contains local primitive variables and reference variables to objects in heap space.

Are references stored in memory?

A reference refers to the object or is bound to the object. You can consider it an alias of the variable name. The variable name doesn't use any memory either. It doesn't need to be stored in memory.

Where is reference variable stored in Java?

The Stack section of memory contains methods, local variables and reference variables. The Heap section contains Objects (may also contain reference variables).


1 Answers

That is left unspecified, and for good reason. The real answer is: it depends on the reference. It can be represented as a normal pointer, or it may not exist at all.

If you have a function-local reference with automatic storage duration, such as this r:

void foo()
{
  int x[4] = {0, 1, 2, 3};
  int &r = x[1];
  // more code
}

then it will probably not take up any space at all. The compiler will simply treat all uses of r as an alias for x[1], and access that int directly. Notice that such alias-style references can also result from function inlining.

On the other hand, if the reference is "persistent" or visible to other translation units (such as a data member or a global variable), it has to occupy some space and be stored somewhere. In that case, it will most likely be represented as a pointer, and code using it will be compiled to dereference that pointer.

Theoretically, other options would also be possible (such as a lookup table), but I don't think those are used by any real-world compiler.

like image 82
Angew is no longer proud of SO Avatar answered Oct 19 '22 23:10

Angew is no longer proud of SO