Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How references are internally stored in c++? [duplicate]

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.

like image 772
howtechstuffworks Avatar asked Feb 18 '12 14:02

howtechstuffworks


People also ask

Where are reference variables stored in C?

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.

How are reference variables stored in memory?

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.

Which memory is used to store references?

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.

Are references implemented as pointers?

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.


1 Answers

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.

like image 125
Kerrek SB Avatar answered Oct 13 '22 19:10

Kerrek SB