GCC 4.8.x 中处理灵活数组成员的错误

Bug in GCC 4.8.x Handling Flexible Array Member?

本文关键字:数组 组成员 错误 处理 GCC      更新时间:2023-10-16

我有以下代码:

#include <cstdint>
struct parent
{
   uint64_t   id;    
   char       data[];
};
struct child : public parent
{
   uint32_t tmp;
   char text[];
};
int main() {
    child d;
    d.id = 1;
}

当使用 GCC 7.2.1 编译时,它给了我错误:

flex.cpp:6:20: error: flexible array member ‘parent::data’ not at end of ‘struct child’
    char       data[];
                    ^
flex.cpp:11:13: note: next member ‘uint32_t child::tmp’ declared here
    uint32_t tmp;
             ^~~
flex.cpp:9:8: note: in the definition of ‘struct child’
 struct child : public parent
        ^~~~~

使用 GCC 4.8.5 编译时,没有警告或错误就可以了。

GCC 4.8.5 中的错误?

提前感谢!

是的,这看起来像 GCC 4.8 中的一个错误。 子类使用的内存在超类的内存之后。 灵活数组成员在语法上位于超类的末尾,但不适用于整个对象的内存布局。 这类似于涉及组合的C案例:

struct parent
{
   uint64_t   id;    
   char       data[];
};
struct child
{
   struct parent parent;
   uint32_t tmp;
   char text[];
};

这也不是有效的 C,尽管 GCC 7 及更早版本只警告-pedantic(在我看来这有点鲁莽(。

请注意,灵活的数组成员是 GNU 扩展,而不是 C++ 标准的一部分。