c++ - GCC 4.8.x 中的 Bug 处理灵活数组成员?

标签 c++ g++

我有以下代码:

#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 中的错误。子类使用的内存在父类(super class)之后。灵活的数组成员在语法上位于父类(super class)的末尾,但不是整个对象的内存布局。这类似于涉及组合的 C 案例:

struct parent
{
   uint64_t   id;    
   char       data[];
};

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

这也不是有效的 C,尽管 GCC 7 和更早版本仅使用 -pedantic 发出警告(在我看来这有点鲁莽)。

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

关于c++ - GCC 4.8.x 中的 Bug 处理灵活数组成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47222731/

相关文章:

c++ - 如何区分 Libav/ffmpeg 中相同的相机?

c++ - 从caffe中提取特征

macos - macosx-version-min 是什么意思?

c++ - 与模板类的链接错误

c++ - 为什么 g++ 10.1 会提示头文件中的命名 lambda 而其他人则不会?

c++ - 与 const 引用关联的临时对象的生命周期(方法链接)

c++ - 如何在类里面使用 cv::setMouseCallback?

c++ - 循环比较(优化)

c++ - 在 linux 下的 c++ 程序中包含 amp.h 库

c++ - 为什么可以在g++(gcc)中重新定义gnulib?