Hello guys) I would love to get an answer for this question: Let me share a small portion of code I have written in C :
#include <iostream>
using namespace std;
int main() {
int* ptr;
int var = 7;
ptr = &var;
cout << "var address:" << &var << endl;
int &ref = var;
cout << "ref address:" << &ref << endl;
cout << "Var value: " << var << endl;
cout << "ref value: " << ref << endl;
return 0;
}
after writing this block of code, I've realized that the addresses that store the variables var and ref are equal. The values these two variables store are the same too. However, I just don't get it in terms of actual numbers of variables the OS memory has allocated for: did the OS allocate memory for ref and var separately or did it allocate only 1 spot in memory for these two(var and ref) variables (if so, does it mean that the spot in memory has two names/identifiers (ref and var)?
I have tried to understand what is actually going on in memory and how does it allocate memory. I wanted to know also how the memory system is actually designed since I cannot comprehend this problem just by drawing box/pointer diagrams.
CodePudding user response:
References are not objects and don't have all the basic properties of object such as storage or size. There may be no storage to get an address to. If you try to get the address or size of a reference, you will instead get the address of the referred object or the size of the referred object.
From https://en.cppreference.com/w/cpp/language/reference :
References are not objects; they do not necessarily occupy storage, although the compiler may allocate storage if it is necessary to implement the desired semantics
So a reference might occupy addressable storage, but only when the implementation needs that storage to implement reference semantics (such as by using a pointer in the background). But this is an implementation detail. It is mostly hidden from the developer, and even then trying to get its address will still give a pointer to the referred object instead.
Note that pointers are objects. They occupy storage, have a size and their address can be obtained with &
, just like an int
. This is why you observe different behavior with references and with pointers.
CodePudding user response:
In general, references are glorified pointers, that auto-deference on use, can't be changed to point to a different object after being created, and aren't allowed to be null.
In simple cases like this one, the reference will almost surely be optimized away, and every access to ref
will be replaced directly with var
.
But in general case, they occupy storage like pointers, though you can't easily get the address of that storage, because applying &
to a reference returns the address of the target object.