Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
57 views
in Technique[技术] by (71.8m points)

How does a C++ reference look, memory-wise?

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
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...