From this question, and consequently, from the Standard (ISO C++-03):
It is unspecified whether or not a reference requires storage (3.7).
In some answers in that thread, it's said that references have, internally, the same structure of a pointer, thus, having the same size of it (32/64 bits).
What I'm struggling to grasp is: how would a reference come not to require storage?
Any sample code exemplifying this would be greatly appreciated.
Edit:
From @JohannesSchaub-litb comment, is there anything like, if I'm not using a const &
, or if I'm using a const &
with default value, it requires allocation? It seems to me, somehow, that there should be no allocations for references at all -- except, of course, when there are explicit allocations involved, like:
A& new_reference(*(new A())); // Only A() instance would be allocated,
// not the new_reference itself
Is there any case like this?
Take something simple:
int foo() {
int x = 5;
int& r = x;
r = 10;
return x;
}
The implementation may use a pointer to x
behind the scenes to implement that reference, but there's no reason it has to. It could just as well translate the code to the equivalent form of:
int foo() {
int x = 10
return x;
}
Then no pointers are needed whatsoever. The compiler can just bake it right into the executable that r
is the same as x
, without storing and dereferencing a pointer that points at x
.
The point is, whether the reference requires any storage is an implementation detail that you shouldn't need to care about.