c++ - 作为唯一的类成员的引用给出了整数的大小 8

标签 c++ reference sizeof class-members

我在编写一个小型 C++ 程序来测试作为类成员的引用时遇到了这种情况。

仅作为类(class)成员提供引用,该计划给出的 o/p 为 8。 一般来说,引用给出的大小与其所属的特定数据类型有关。但为什么这里是 8(而不是 4)。请帮助我理解它。

#include<iostream>
using namespace std;

class Test {
    int &t;
public:
    Test(int &t):t(t) {}
};

int main()
{
    int x = 20;
    Test t1(x);
    int &ref = x;
    cout<<sizeof(ref)<<endl;
    cout<<sizeof(t1)<<endl;
    return 0;
}

输出 -

/home/user>./a.out
4
8

最佳答案

[expr.sizeof]

2 When applied to a reference or a reference type, the result is the size of the referenced type. When applied to a class, the result is the number of bytes in an object of that class including any padding required for placing objects of that type in an array.

sizeof 引用将返回所引用对象的大小,在 sizeof(ref) 的情况下,这相当于 sizeof(int) ,在您的平台上是 4。

另一方面,您的类需要存储对 int 的引用,该标准没有指定实现应如何实现这一点,但它们通常(如果不是普遍的话)存储为指针后面场景。你的平台上的 sizeof(int*) 大概是 8,但细节并不重要,你只需要知道 sizeof(Test) 是 8。

关于c++ - 作为唯一的类成员的引用给出了整数的大小 8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30746062/

相关文章:

具有 move 语义的 C++ 可变工厂导致运行时崩溃

c++ - setter 导致段错误

c++ - Mersenne Twister 种子作为成员变量

c++ - 传递对指针的引用

c++ - C/C++ 中的 sizeof char* 数组

c++ - 将(同步)堆栈分配的内存传递给其他线程是否安全?

C++ 参数应按值传递,但编译器将其视为引用

python - 赋值只是将名称绑定(bind)到对象?

c - 带位域​​的打包结构的 Sizeof

c++ - 指针地址的区别