为什么参考大小总是4个字节 - c ++ [英] why reference size is always 4 bytes - c++

查看:157
本文介绍了为什么参考大小总是4个字节 - c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在32位机器上,我总是得到一个引用4字节的 sizeof ,即使它是一个double的引用,那么它真正存储在这4字节。



编辑:

  {
public:
double&一个;
};

int main(){
cout<< sizeof(A)< endl; // this will print out 4
}


解决方案

sizeof (C ++ 11,5.3.3 / 4)的标准很清楚:


当应用于引用类型或引用类型时,结果是引用类型的
大小。


所以,如果你真的采取 sizeof(double&),编译器告诉你 sizeof(double)是4。



更新:所以,你真正做的是应用 sizeof 到类类型。在这种情况下,


当应用于类时,结果是该类的
对象中的字节数[ ...]


所以我们知道 A 使其占用4个字节。这是因为即使标准不要求如何实现引用,编译器仍然必须以某种方式实现它们。这取决于上下文,可能会有很大的不同,但对于类类型的引用成员,唯一的方法是偷偷在 double * 后面和调用



所以如果你的架构是32位的(其中指针是4

请注意,引用的概念并不局限于任何特定的实现。

该标准允许编译器实现它想要的引用。


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
}

解决方案

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.

这篇关于为什么参考大小总是4个字节 - c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆