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

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

问题描述

在 32 位机器上,我总是得到 4 个字节的引用的 sizeof ,即使它是对双精度的引用,那么它在这 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.

class A{
public:
  double&  a;
};

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

推荐答案

sizeof (C++11, 5.3.3/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.

所以如果你真的使用 sizeof(double&),编译器会告诉你 sizeof(double) 是 4.

So if you really are taking sizeof(double&), the compiler is telling you that sizeof(double) is 4.

更新: 所以,您真正要做的是将 sizeof 应用于类类型.在这种情况下,

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 [...]

所以我们知道 A 中引用的存在导致它占用 4 个字节.这是因为即使标准没有规定如何实现引用,编译器仍然必须以某种方式实现它们.这在某种程度上可能会因上下文而有很大不同,但是对于类类型的引用成员,唯一有意义的方法是在背后偷偷地使用 double* 并将其称为 double& 在你的脸上.

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.

因此,如果您的体系结构是 32 位(其中指针长度为 4 个字节),那可以解释结果.

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天全站免登陆