简体   繁体   中英

What happen to stack when i declare a reference variable? C++

When i declare a variable, it will be allocated in stack at a certain index of memory right?

But when i declare a reference variable it will point to the same index of the other one, so no new space have to be allocated in stack...

How does the c++ handle this situation?

i mean pratically, it have a table that contains the association between names and indexes?

The compiler do all the work?

I hope to be clear... If anybody have some manuals or stuff about that i'll be very pleased!

Thanks to all and sorry if i wrote in a bad english!

The C++ standard does not specify ABI so this is implementation-defined. But the usual approach is that a reference is implemented as a pointer and so a pointer is allocated on stack. However if this reference is not passed anywhere, it may be optimized away and simply replaced by the variable it points to.

On a typical implementation, the allocation of the variable depends on how you declare it and where you declare it.

Commonly, variables defined outside of a function are placed in one area of memory (neither stack nor heap). Constants may be placed in a different area or in the executable.

Variables defined inside a function that are not static may be allocated on the stack. They could be placed in registers and not on the stack. Depends on the compiler and the optimization settings. The variables could be "optimized away" and not exist in the final executable.

Many compilers treat references like pointers. So when you pass a variable by reference, the compiler may pass by pointer.

C++14 [dcl.ref]/4 says:

It is unspecified whether or not a reference requires storage

For a situation like int a; int &b = a; int a; int &b = a; the compiler may indeed just store two identifiers that both refer to the same address in its table of identifiers while compiling. There would probably be no extra runtime storage required here. Indeed, the rules of C++ say that int b; int &a = b; int b; int &a = b; results in exactly the same situation.

When a function accepts a parameter by reference: if the compiler was not able to optimize over the function call then it is likely that an address will be passed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM