I was just wondering, how references are internally stored? I felt that an understanding deep down that level will make me understand the concept pointer vs reference better and making decision choices.
I suspect that it basically works same as pointers but the compiler takes care of handling pointers. Please advise.
Reference type stored in heap not stack. A reference is stored on heap because dynamically allocation is stored in heap and reference create at run time. So yes its 100% right. Stack is used to store local variable basically.
Reference Type variables are stored in a different area of memory called the heap. This means that when a reference type variable is no longer used, it can be marked for garbage collection. Examples of reference types are Classes, Objects, Arrays, Indexers, Interfaces etc.
An object reference variable must then hold a reference to those values. This reference represents the location where the object and its metadata are stored. There are two kinds of memory used in Java. These are called stack memory and heap memory.
Reference is not pointer. This is fact. Pointer can bind to another object, has its own operations like dereferencing and incrementing / decrementing. Although internally, reference may be implemented as a pointer.
There's no requirement that a reference be "stored" in any way at all. As far as the language is concerned, a reference is just an alias of some existing object, and that's all that any compiler must provide.
It's entirely possible that there's no need to store anything at all if the reference is just a short-hand for some other object that's already in scope, or if a function with a reference argument gets inlined.
In situations where the reference needs to be made manifest (e.g. when calling a function in a different translation unit), you can practically implement a T & x
as a T * const
and treat every occurrence of x
as implicitly dereferencing that pointer. Even on a higher level you can think of T & x = y;
and T * const p = &y;
(and correspondingly of x
and *p
) as essentially equivalent, so this would be an obvious way to implement references.
But of course there's no requirement, and any implementation is free to do whatever it wants.
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