Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

why reference size is always 4 bytes - c++

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
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...