Possible Duplicate:
size of reference variable in c++
Do C++ references consume any memory? If not, how can they be passed as arguments to functions?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Sometimes they do and sometimes they don’t. When they need to (such as when used as data members), they do.
For an example where they don’t need to:
Now, the compiler can treat
bpurely as an alias fora. There is never a requirement to allocate memory forbhere, because references aren’t objects.Another case that may be of interest:
In this case
cis a reference to the temporary object that is the return value of the call. The temporary’s life is extended to the scope ofc, so in that sense you could say thatcconsumes an int-sized piece of memory. But there’s no particular reason that the compiler needs to allocate any more than that. You might see the same emitted code as if you’d writtenconst int c = some_function_call();, which also creates anintobject with identical lifetime and the same namec.As for passing them as parameters — it depends on the calling convention whether parameters occupy memory or not. Some parameters might get passed in registers. Then it depends on the callee code whether that register ends up getting spilled to stack somewhere during the execution of the function. But yes, when passed as parameters and the function call not inlined, reference parameters must occupy “something”, because the caller must somehow let the callee know the address of the object referred to by the reference (the “referand”).
All the same things can be said of pointers provided that you don’t take the address of the pointer. But in the case of pointers it’s an optimization on the compiler’s own initiative. In the case of references they’re explicitly defined in the standard to be aliases, and pointers (or at any rate addresses) happen to be the obvious means to implement that in cases where the compiler can’t treat a reference purely as an entry in its compile-time name lookup table. The only essential difference is what happens in the abstract machine described by the standard — after implementation and optimization it may well amount to the same thing.