在C++中继承C结构并将其传递回C库是否安全?

YiF*_*Fei 2 c c++ oop inheritance casting

基本上,我希望在C++中继承一个C结构(好吧,字面意思).我有:

struct foo { // C-side definition
    int sz;
    /* whatever */
    // no virtual destructor, special mechanism
};

class cxx_class { 
    /* something here */
    // no virtual destructor, no need
};

class derived : public foo /*, public cxx_class */ {
    /* some other stuff here */
};
Run Code Online (Sandbox Code Playgroud)

derived实例(以形式foo*)将被传递回外部库,外部库只知道并使用(当然)的foo部分derived.但问题是(我假设)库只使用c-style强制转换,这相当于reinterpret_cast在C++中,fooin derived必须位于内存块的开头.

我想知道这是否是定义的行为并且标准保证这个吗?


换一种说法:

编辑: 这两个问题与答案指出的不一样,这部分没有回答.

有时候我会static_cast用于垂头丧气.但是一些代码使用reinterpret_cast是否保证两者总是给出相同的答案?

小智 7

derived实例(以形式foo*)将被传递回外部库,外部库只知道并使用(当然)的foo部分derived.

如果你的功能需要foo*,那没关系.即使在这样的方式构建你的类型foo没有放置之初derived,从转换derived*foo*发生在C++代码,不知道这个类型的布局.然后外部功能不需要担心它.