Issue
Given:
int i = 42;
int j = 43;
int k = 44;
By looking at the variables addresses we know that each one takes up 4 bytes (on most platforms).
However, considering:
int i = 42;
int& j = i;
int k = 44;
We will see that variable i
indeed takes 4 bytes, but j
takes none and k
takes again 4 bytes on the stack.
What is happening here? It looks like j
is simply non-existent in runtime. And what about a reference I receive as a function argument? That must take some space on the stack...
And while we're at it - why can't I define an array or references?
int&[] arr = new int&[SIZE]; // compiler error! array of references is illegal
Solution
everywhere the reference j is encountered, it is replaced with the address of i. So basically the reference content address is resolved at compile time, and there is not need to dereference it like a pointer at run time.
Just to clarify what I mean by the address of i :
void function(int& x)
{
x = 10;
}
int main()
{
int i = 5;
int& j = i;
function(j);
}
In the above code, j should not take space on the main stack, but the reference x of function will take a place on its stack. That means when calling function with j as an argument, the address of i that will be pushed on the stack of function. The compiler can and should not reserve space on the main stack for j.
For the array part the standards say ::
C++ Standard 8.3.2/4:
There shall be no references to references, no arrays of references, and no pointers to references.
Why arrays of references are illegal?
Answered By - Khaled Alshaya Answer Checked By - Senaida (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.