我有以下代码:
#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/