c ++:错误:基类有一个灵活的数组成员

And*_*mas 2 c++ clang

我已将我的工作环境从ubuntu 12.04升级到14.04.这导致我的编译器的升级clang,从3.0-6ubuntu33.4-1ubuntu3.

当我编译我的代码时,我收到一个错误,我没有用来得到:

error: base class has a flexible array member
Run Code Online (Sandbox Code Playgroud)

我按照代码,发现我正在使用inotify.h:

#include <sys/inotify.h>
Run Code Online (Sandbox Code Playgroud)

在这个文件里面有这个结构:

struct inotify_event {
    int     wd;     /* watch descriptor */
    uint32_t        mask;       /* watch mask */
    uint32_t        cookie;     /* cookie to synchronize two events */
    uint32_t        len;        /* length (including nulls) of name */
    char        name __flexarr; /* stub for possible name */
};
Run Code Online (Sandbox Code Playgroud)

接下来,我读到了__flexarr这里,但我没有设法理解出了什么问题或者我如何解决它.任何帮助将不胜感激.


更新:作为BobTFish答案的后续内容,这里是在我的代码中使用inotify_event.

我有一个名为class的类inotify_condition_c,它有一个inotify_eventlet 类型的成员m_notify_event.

我有几个继承自的类inotify_condition_c.编译错误clang返回指向那些派生类.

这不是我们回购中很长一段时间的新鳕鱼.我仍然不明白为什么从ubuntu 12.04升级到14.04(以及clang新版本)也显示错误.

BoB*_*ish 5

__flexarr是一个C技巧,你在一个结尾处放置一个空数组struct,然后在你的实例之后立即放置你想要的数据struct,这样你就可以将额外的数据视为数组的一部分.因此inotify_event:

|wd|mask|cookie|len|name|some|extra|data|
                         ^^^^^^^^^^^^^^^ can be accessed with name[0], name[1], etc.
Run Code Online (Sandbox Code Playgroud)

如果有一个类继承自另一个类:

struct Base {
    int a;
};
struct Derived : Base {
    int b;
}
Run Code Online (Sandbox Code Playgroud)

它(通常)将被布置在内存中,以便数据Derived立即跟随以下数据Base:|a|b|

应该清楚的是,这两种技术是不相容的.因此,当您尝试使用灵活数组从类派生时,clang似乎引入了一个错误,例如inotify_event.

代码中的某处,某些东西是继承自的inotify_event.你不能这样做.

然而,在我们看到该课程之前,我们无法建议如何修复它.如果您能找到该课程,将其编辑到您的问题中,并解释如何使用它,我们可能会进一步提供帮助.

编辑:
最不好的(即不涉及某种程度的UB)解决方案,我可以想到的是inotify_event通过动态分配它来存储类的外部.std::unique_ptr<inotify_event>在您的班级中存储一名成员,然后将其设置为std::make_unique<inotify_event>().然后将其视为普通指针,但不要担心new/ delete.

所以它涉及额外的分配,但我能想到的另一个解决方案涉及一个看起来几乎像的虚拟类inotify_event,以及一个非常可疑的演员.

另一种可能性是存储重建所需的数据inotify_event,并在每次需要时在本地创建新数据.我不知道在您的情况下,终身问题是否允许这样做.