代码之家  ›  专栏  ›  技术社区  ›  Glenn Teitelbaum

在C++标准中访问BITFELL联盟常见的初始数据未定义行为

  •  1
  • Glenn Teitelbaum  · 技术社区  · 6 年前

    c union and bitfields 但是在 C++ 包括对初始序列的访问

    类似 Union common initial sequence with primitive 但是使用 bitfields

    struct A
    {
       short common : 1;
       short a1: 5;
       short a2: 8;
    };
    
    struct B
    {
       short common : 1;
       short b1: 3;
       short b2: 4;
       short b3: 6;
    };
    
    union C
    {
        A a;
        B b;
    };
    

    然后按如下方式使用:

    short foo(C data)
    {
       if (data.a.common)
       {
           return data.a.a1*data.a.a2;
       }
       return data.b.b1*data.b.b2*data.b.b3;
    }
    

    问题是如果 data.a.common B 通过的成员 A

    common 作为一个 bitfield 会算数的

    9.5.1允许检查任何标准布局结构构件的通用初始顺序;

    如有任何澄清,将不胜感激

    1 回复  |  直到 6 年前
        1
  •  1
  •   Language Lawyer    6 年前

    the definition of common initial sequence

    两个标准布局结构([class.prop])类型的公共初始序列是声明顺序中非静态数据成员和位字段的最长序列,从每个结构中的第一个此类实体开始,以便相应的实体具有布局兼容类型,要么两个实体都用no_unique_address属性([dcl.attr.nonuiqueadr])声明,要么都不是,要么两个实体都是具有相同宽度的位字段,要么都不是位字段。

    共同的初始序列 struct A struct B 由第一位字段组成 common

    推荐文章