The standard is pretty clear on sizeof
(C++11, 5.3.3/4):
When applied to a reference or a reference type, the result is the
size of the referenced type.
So if you really are taking sizeof(double&)
, the compiler is telling you that sizeof(double)
is 4.
Update: So, what you really are doing is applying sizeof
to a class type. In that case,
When applied to a class, the result is the number of bytes in an
object of that class [...]
So we know that the presence of the reference inside A
causes it to take up 4 bytes. That's because even though the standard does not mandate how references are to be implemented, the compiler still has to implement them somehow. This somehow might be very different depending on the context, but for a reference member of a class type the only approach that makes sense is sneaking in a double*
behind your back and calling it a double&
in your face.
So if your architecture is 32-bit (in which pointers are 4 bytes long) that would explain the result.
Just keep in mind that the concept of a reference is not tied to any specific implementation. The standard allows the compiler to implement references however it wants.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…