Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What value does a Reference Variable in C++ store?

Tags:

c++

A pointer stores/is assigned a memory address;

what about a reference variable?

it stores the actual value of an object just like any other non-pointer simple variables on Stack?

Thanks!

like image 446
user36064 Avatar asked Nov 28 '22 12:11

user36064


1 Answers

A reference does contain nothing in itself. The C++ Standard even states that an implementation is not required to allocate any storage for a reference. It's really just an alias for the object or function that it references. Trying to take the value of a reference will take the value of the object or function (in that case, you get a function pointer, just like when you would try to get the value out of the function using its original name) it references, instead.

Of course, when you go on lower levels and look at the assembler code, references are just like pointers. But at the language level, they are completely different beasts. References to const, for example, can bind to temporaries, they are required to implement a copy constructor, for overloading operators and they can't be put into an array (not even if you initialize all elements of it), because references are no objects (as opposed to pointers). They are, as trivial as it may sound, reference types.

like image 112
Johannes Schaub - litb Avatar answered Dec 10 '22 05:12

Johannes Schaub - litb