我正在使用平面缓冲区对对象进行序列化以通过网络传输,问题是FlatBufferBuild超出范围后缓冲区是否仍然有效,例如:

char* GetBuffer(...size_t &size) {
    flatbuffers::FlatBufferBuilder fbb;
    flatbuffers::Offset<MyStruct> data = CreateMyStruct(fbb, ...);
    FinishMyStructBuffer(fbb, data);
    size = fbb.GetSize();
    return fbb.GetBufferPointer();
}

size_t size;
char* mybuf = GetBuffer(..., size);
do(mybuf, size);


我使用的mybuf是否有效的内存缓冲区?谢谢。

最佳答案

您对mybuf的用法无效,这将导致未定义的行为,因为FlatBufferBuilder在调用其析构函数时会破坏内部缓冲区。我建议使用DetachedBuffer如下:

flatbuffers::DetachedBuffer GetBuffer(...) {
    flatbuffers::FlatBufferBuilder fbb;
    flatbuffers::Offset<MyStruct> data = CreateMyStruct(fbb, ...);
    FinishMyStructBuffer(fbb, data);
    return fbb.Release();
}

flatbuffers::DetachedBuffer mybuf = GetBuffer(...);
do(mybuf);


请注意,DetachedBuffer将拥有底层缓冲存储器,并在调用析构函数后将其释放。

09-09 23:58