代码之家  ›  专栏  ›  技术社区  ›  Fanatic23

64位环境中引用的大小

  •  6
  • Fanatic23  · 技术社区  · 14 年前

    References Vs Variable Gets ). 我的问题是,对于所有64位环境,是否保证即使原始变量的大小较小,对变量的引用也是64位的?与64位环境中的char引用一样,>sizeof(char)?标准中有没有明确规定这一点的章节?

    编辑:为了更清楚-- 字符c1='a'; 我的问题是64位机器中的sizeof(c2)>sizeof(c1)?

    3 回复  |  直到 7 年前
        1
  •  13
  •   Community CDub    7 年前

    标准(ISOC+++03)表示以下参考文献

    It is unspecified whether or not a reference requires storage (3.7).

    如果我错了或者我没有正确理解他的问题,请有人纠正我。

    编辑 :

    我的问题是64位机器中的sizeof(c2)>sizeof(c1)?

    不,作为 @Chubsdad 注意到 sizeof(c2) = sizeof (c1)

    When applied to a reference or a reference type, the result is the size of the referenced type . (ISO C++ +5.3.3/2)

        2
  •  8
  •   Chubsdad    14 年前

    It is unspecified whether or not a reference requires storage.

    sizeof应用于引用基本上是refererand的大小。

    因此,如果“r”是对“i”的整数引用,那么如果“r”有实际存储,则未指定。然而 sizeof(r) 内部代表 sizeof(i) .

    如果“r”是对“char”的引用,则 将永远 sizeof(char) == 1

        3
  •  4
  •   Jonathan Leffler    14 年前

    尽管 sizeof(ref_var)

    #include <iostream>
    using namespace std;
    
    char  c1 = 'a';
    char &c2 = c1;
    struct x
    {
        char  c1;
        char  c2;
        char  c3;
        char  c4;
        int   i4a;
        char &r1; 
        int   i4b;
        int   i4c;
        x() : r1(c1) { }
    };
    struct y
    {
        char  c1;
        char  c2;
        char  c3;
        char  c4;
        int   i4a;
        int   i4b;
        int   i4c;
    };
    int main()
    {
        cout << sizeof(c2) << endl;
        cout << sizeof(y) << endl;
        cout << sizeof(x) << endl;
        return 0;
    }
    

    我并不自诩它是“伟大的代码”-它不是-但它证明了一点。在MaOSx0.4.4上编译的C++编译器从GNU编译器集合(GCC 4.5.1)中默认(64位)模式,输出为:

    1
    16
    24
    

    1
    16
    20
    

    输出的第一行显示 sizeof(参考变量) sizeof(int) == 4 )在64位编译时比简单结构大8字节,在32位编译时比简单结构大4字节。由此推断,结构的引用部分在64位编译时占用4字节以上,不超过8字节,在32位编译时占用不超过4字节。这表明(至少在一个流行的C++实现中)结构中的引用占用了与指针相同的空间量,正如在一些其他答案中所声明的那样。

    因此,它可能依赖于实现,但引用与指针占用相同空间的注释至少在一个(相当广泛使用的)实现中是正确的。

    推荐文章