On a 32-bit machine I always get the sizeof
of a reference 4 bytes even if it\'s a reference to a double, so what does it really store in this 4 bytes.
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.
You can't, and it isn't.
A C++ reference is not a pointer. It is an alias of an object. Sometimes, the compiler chooses to implement this by using a pointer. But often, it implements it by doing nothing at all. By simply generate code which refers directly to the original object.
In any case, sizeof
applied to a reference type does not give you the size of a reference. So it's not really clear what you're doing, making it impossible to explain what is happening.
Edit
Now that you've shown some code, we can answer the question:
You are taking the size of a class containing a reference. As I said above, a reference is not a pointer, but when necessary, the compiler may fall back to using a pointer to represent it. When you create a class containing a reference, the only (sane) way the compiler can implement it is by defining a class which holds the address of an object. On 32-bit systems, addresses are 32 bits, or 4 bytes, wide. So sizeof
such a class will (typically) be 4.