c++ - 引用内存分配技术

标签 c++ reference sizeof

我对引用的大小感到困惑
我已经举了两个例子并编译了它

//示例程序

#include <iostream>
#include <string>

using namespace std;

class ABC
{

    int &y;
    ABC(int a):y(a)
    {
    }
};
int main()
{
  std::cout <<sizeof(ABC)<<endl;  
  return 0;
}

o/p - 8

当我在课外获取引用大小时

//示例程序

#include <iostream>
#include <string>

using namespace std;
int main()
{
    int y = 7;
    int &x = y;

    cout<<sizeof(x);
}

o/p - 4

请确认为什么引用的大小在类的一侧或函数内部不同。

最佳答案

why the size of reference differ in side of class or inside a function.

因为sizeof计算出来的对象不一样。对于 sizeof(x)sizeof operator将返回引用类型的大小,即 int

When applied to a reference type, the result is the size of the referenced type.

sizeof(ABC) 将返回包含引用的类 ABC 的大小。它们不是一回事。

请注意,对于类包含引用的情况,标准并未说明引用应如何实现以及表示的大小应该是多少,但在大多数实现中,引用将作为指针实现,并且在 64-位系统,地址是 64 位,因此您可能会得到 8 的结果。

关于c++ - 引用内存分配技术,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37919703/

相关文章:

reference - 是否可以检查 SMLNJ 中的指针相等性(用于调试)?

用于唯一对象实例的 Java Map?

c - 带有条件的循环中的 scanf() 不起作用

c++ - 将 lambda 函数传递给通用函数 C++

c++ - 如何在 C++ 中读取和解析 CSV 文件?

c++ - 如何实现创建新对象并返回对它的引用的 C++ 方法

c - 获取指针数据的大小

c - 应用于数组类型的 sizeof

c++ - 如何为 Qt 应用程序创建可执行文件?

c++ - boost::geometry multi_point 不能像多边形那样构造