diff --git a/include/flatbuffers/flatbuffers.h b/include/flatbuffers/flatbuffers.h index 9f6849a15..12de917ed 100644 --- a/include/flatbuffers/flatbuffers.h +++ b/include/flatbuffers/flatbuffers.h @@ -1545,6 +1545,12 @@ class FlatBufferBuilder { reinterpret_cast(buf)); } + template + Offset> CreateUninitializedVectorOfStructs(size_t len, T **buf) { + return CreateUninitializedVector(len, sizeof(T), + reinterpret_cast(buf)); + } + /// @brief Write a struct by itself, typically to be part of a union. template Offset CreateStruct(const T &structobj) { NotNested(); diff --git a/tests/monster_test.bfbs b/tests/monster_test.bfbs index a6b87d4a4..6d4a68113 100644 Binary files a/tests/monster_test.bfbs and b/tests/monster_test.bfbs differ diff --git a/tests/test.cpp b/tests/test.cpp index 4bd85988e..4a2ee2788 100644 --- a/tests/test.cpp +++ b/tests/test.cpp @@ -1950,6 +1950,34 @@ void EndianSwapTest() { TEST_EQ(flatbuffers::EndianSwap(flatbuffers::EndianSwap(3.14f)), 3.14f); } +void UninitializedVectorTest() { + flatbuffers::FlatBufferBuilder builder; + + Test *buf = nullptr; + auto vector_offset = builder.CreateUninitializedVectorOfStructs(2, &buf); + TEST_NOTNULL(buf); + buf[0] = Test(10, 20); + buf[1] = Test(30, 40); + + auto required_name = builder.CreateString("myMonster"); + auto monster_builder = MonsterBuilder(builder); + monster_builder.add_name(required_name); // required field mandated for monster. + monster_builder.add_test4(vector_offset); + builder.Finish(monster_builder.Finish()); + + auto p = builder.GetBufferPointer(); + auto uvt = flatbuffers::GetRoot(p); + TEST_NOTNULL(uvt); + auto vec = uvt->test4(); + TEST_NOTNULL(vec); + auto test_0 = vec->Get(0); + auto test_1 = vec->Get(1); + TEST_EQ(test_0->a(), 10); + TEST_EQ(test_0->b(), 20); + TEST_EQ(test_1->a(), 30); + TEST_EQ(test_1->b(), 40); +} + int main(int /*argc*/, const char * /*argv*/ []) { // clang-format off #if defined(FLATBUFFERS_MEMORY_LEAK_TRACKING) && \ @@ -2020,6 +2048,7 @@ int main(int /*argc*/, const char * /*argv*/ []) { JsonDefaultTest(); FlexBuffersTest(); + UninitializedVectorTest(); if (!testing_fails) { TEST_OUTPUT_LINE("ALL TESTS PASSED");