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.
EDIT :
class A{
public:
double& a;
};
int main(){
cout << sizeof(A) << endl; // this will print out 4
}
Size of a pointer is fixed for a compiler. All pointer types take same number of bytes for a compiler. That is why we get 4 for both ptri and ptrc.
A pointer in this case is 4 bytes because a 32bit processor uses 32 bit addresses so it can address 232 discrete memory locations (4Gb).
why reference size is always 4 bytes - c++
3. Size of a Pointer to Pointer. As we already know, the size of the pointer in C is dependent only on the word size of a particular system. So, the size of a pointer to a pointer should have the usual values, that is, 2 bytes for a 16-bit machine, 4 bytes for a 32-bit machine, and 8 bytes for a 64-bit machine.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With