我对引用的大小感到困惑
我已经举了两个例子并编译了它
//示例程序
#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/