最近,我尝试在C ++中使用FlatBuffers。我发现flatBuffers似乎在C ++中使用了很多类型的修饰,例如reinterpret_cast。这使我有些不舒服,因为我已经学会了it's undefined behavior in many cases。
例如Rect
在fbs文件中:
struct Rect {
left:int;
top:int;
right:int;
bottom:int;
}
变成此C ++代码以从表中读取它:
const xxxxx::Rect *position() const {
return GetStruct<const xxxxx::Rect *>(VT_POSITION);
}
和the definition of GetStruct仅使用reinterpret_cast。
我的问题是:
- 这是C ++中真正未定义的行为吗?
- 在实践中,这种用法实际上会出现问题吗?
更新:
缓冲区只能来自网络或磁盘。我不知道缓冲区是否实际上来自同一C ++程序的编写者编写的同一内存是否不同。
但是作者的自动生成方法是:
void add_position(const xxxxx::Rect *position) {
fbb_.AddStruct(Char::VT_POSITION,position);
}
将使用this method和this method,因此也使用reinterpret_cast。