基本上,我想继承 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 */
};
derived
实例(以 foo*
的形式)将被传递回外部库,该库只知道并使用 foo
部分derived
(当然)。但问题是(我假设)该库仅使用 c 风格的转换,相当于 C++ 中的 reinterpret_cast
,derived
中的 foo
> 必须在内存块的开头。
我想知道这是否是定义的行为,标准是否保证这一点?
换句话说:
编辑: 这两个问题与答案指出的不一样,这部分没有回答。
有时我使用 static_cast
进行向下转换。但是部分代码使用了reinterpret_cast
是不是保证两者总是给出相同的答案呢?
最佳答案
derived
instances (in form offoo*
) will be passed back to the external library which only knows and uses thefoo
part ofderived
(of course).
如果您的函数采用foo*
,那没关系。即使以 foo
未放在 derived
开头的方式构造您的类型,从 derived*
到 的转换foo*
发生在知道类型布局的 C++ 代码中。外部函数就不需要担心了。
关于c++ - 在 C++ 中继承 C 结构并将其传递回 C 库是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46534366/