I have a class like this, is it valid to return flatbuffer pointer even though builder is created on stack
class Foo {
uint8_t* serialize() {
flatbuffers::FlatBufferBuilder builder(1024);
....
....
return builder.GetBufferPointer();
}
}
From documentation here https://google.github.io/flatbuffers/md__cpp_usage.html
"Calling code may take ownership of the buffer with fbb.ReleaseBufferPointer(). Should you do it, the FlatBufferBuilder will be in an invalid state, and must be cleared before it can be used again. However, it also means you are able to destroy the builder while keeping the buffer in your application."
Look like this should work and returned pointer will point to valid buffer even if builder is destroyed. Can someone confirm this, looks like buffer itself is created on heap.
No, this will not work, you're using GetBufferPointer
which is a naked pointer to memory owned by FlatBufferBuilder
, which will be deallocated upon leaving the function.
Like the docs you quote say, you must use ReleaseBufferPointer
instead. Or make a copy, though that is obviously less efficient.
Better yet to structure your code such that the caller owns FlatBufferBuilder
and its passed as an argument.