A reference is not an object, and unlike an object, it is not guaranteed to occupy some contiguous bytes of memory. The standard leaves it unspecified whether a reference requires any storage at all. A number of features of the language conspire to make it impossible to portably examine any storage the reference might occupy:
sizeof
is applied to a reference, it returns the size of the referenced type, thereby giving no information about whether the reference occupies any storage.offsetof
yields undefined behavior since such a class is not a standard-layout class.In practice, in some cases a reference variable may be implemented similarly to a pointer variable and hence occupy the same amount of storage as a pointer, while in other cases a reference may occupy no space at all since it can be optimized out. For example, in:
void f() {
int x;
int& r = x;
// do something with r
}
the compiler is free to simply treat r
as an alias for x
and replace all occurrences of r
in the rest of the function f
with x
, and not allocate any storage to hold r
.