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.
Reference is one type of variable stored on stack because of there is need to perform operation on them where object stored on 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.
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.
The Stack section of memory contains methods, local variables and reference variables. The Heap section contains Objects (may also contain reference variables).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With