Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why reference size is always 4 bytes - c++

Tags:

c++

reference

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
}
like image 700
AlexDan Avatar asked May 04 '12 10:05

AlexDan


People also ask

Why is pointer size 4 bytes in C?

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.

Why char pointer is 4 bytes?

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).

How many bytes is a reference variable?

why reference size is always 4 bytes - c++

Why size of pointer is 8 bytes in 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.


1 Answers

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.

like image 132
Jon Avatar answered Oct 11 '22 09:10

Jon