The foundational C++ API providing core functionality for buffer creation, data access, verification, and memory management. This forms the basis for all language-specific implementations of FlatBuffers.
The main builder class for constructing FlatBuffer data structures. Manages memory allocation, field addition, and buffer finalization.
template<bool Is64Aware = false>
class FlatBufferBuilderImpl {
public:
/**
* Constructor for FlatBufferBuilder
* @param initial_size Initial buffer size in bytes (default: 1024)
* @param allocator Custom memory allocator (default: nullptr for DefaultAllocator)
* @param own_allocator Whether builder owns the allocator (default: false)
* @param buffer_minalign Minimum buffer alignment (default: AlignOf<largest_scalar_t>())
*/
explicit FlatBufferBuilderImpl(
size_t initial_size = 1024,
Allocator *allocator = nullptr,
bool own_allocator = false,
size_t buffer_minalign = AlignOf<largest_scalar_t>()
);
/** Reset builder state for reuse, keeping allocated memory */
void Clear();
/** Get current buffer size in bytes */
size_t GetSize() const;
/** Create string and return its offset */
Offset<String> CreateString(const char *str);
Offset<String> CreateString(const char *str, size_t len);
Offset<String> CreateString(const std::string &str);
/** Create vector and return its offset */
template<typename T>
Offset<Vector<T>> CreateVector(const T *v, size_t len);
template<typename T>
Offset<Vector<T>> CreateVector(const std::vector<T> &v);
/** Start table construction with specified field count */
void StartTable(uoffset_t num_fields);
/** Complete table construction and return offset */
Offset<Table> EndTable();
/** Add scalar field to current table */
template<typename T>
void AddElement(T element);
/** Add offset field to current table */
template<typename T>
void AddOffset(Offset<T> off);
/** Finalize buffer with root table */
void Finish(Offset<Table> root, const char *file_identifier = nullptr);
/** Get pointer to buffer data */
uint8_t *GetBufferPointer() const;
/** Release buffer ownership and return DetachedBuffer */
DetachedBuffer ReleaseBufferPointer();
/** Get buffer as span/view */
flatbuffers::span<uint8_t> GetBufferSpan() const;
};
// Type aliases for common usage
using FlatBufferBuilder = FlatBufferBuilderImpl<false>; // 32-bit offsets
using FlatBufferBuilder64 = FlatBufferBuilderImpl<true>; // 64-bit offsetsUsage Example:
#include "flatbuffers/flatbuffers.h"
// Create builder
FlatBufferBuilder builder(1024);
// Create strings and vectors
auto name = builder.CreateString("Example");
std::vector<int> numbers = {1, 2, 3, 4, 5};
auto vec = builder.CreateVector(numbers);
// Build table
builder.StartTable(2);
builder.AddOffset(name); // Add string field
builder.AddOffset(vec); // Add vector field
auto table = builder.EndTable();
// Finalize buffer
builder.Finish(table);
// Access result
uint8_t *buf = builder.GetBufferPointer();
size_t size = builder.GetSize();Base class for accessing FlatBuffer table data with zero-copy deserialization and optional field handling.
class Table {
public:
/** Get vtable pointer for this table */
const uint8_t *GetVTable() const;
/** Get field offset or 0 if field not present */
voffset_t GetOptionalFieldOffset(voffset_t field) const;
/** Get field value with default fallback */
template<typename T>
T GetField(voffset_t field, T defaultval) const;
/** Get pointer to offset-based field (strings, vectors, tables) */
template<typename P, typename OffsetSize = uoffset_t>
P GetPointer(voffset_t field);
template<typename P, typename OffsetSize = uoffset_t>
P GetPointer(voffset_t field) const;
/** Get pointer using 64-bit offsets */
template<typename P>
P GetPointer64(voffset_t field);
template<typename P>
P GetPointer64(voffset_t field) const;
/** Get pointer to struct field (stored inline) */
template<typename P>
P GetStruct(voffset_t field) const;
/** Get optional field as Optional<T> */
template<typename Raw, typename Face>
flatbuffers::Optional<Face> GetOptional(voffset_t field) const;
/** Mutate field value (if mutable buffer) */
template<typename T>
bool SetField(voffset_t field, T val, T def);
template<typename T>
bool SetField(voffset_t field, T val);
/** Check if field is present in vtable */
bool CheckField(voffset_t field) const;
/** Verification support */
bool VerifyTableStart(Verifier &verifier) const;
template<typename T>
bool VerifyField(const Verifier &verifier, voffset_t field, size_t align) const;
};Template class for accessing FlatBuffer vector data with STL-compatible interface and zero-copy element access.
template<typename T, typename SizeT = uoffset_t>
class Vector {
public:
/** Get vector length */
SizeT size() const;
/** Check if vector is empty */
bool empty() const;
/** Access element at index (bounds-checked in debug) */
const T *Get(SizeT i) const;
/** Array-style element access */
const T *operator[](SizeT i) const;
/** Get element as enum type */
template<typename E>
E GetEnum(SizeT i) const;
/** Cast element to union type */
template<typename U>
const U *GetAs(SizeT i) const;
/** Mutate element in-place (if mutable buffer) */
bool Mutate(SizeT i, const T &val);
/** Binary search by key (requires sorted vector) */
template<typename K>
const T *LookupByKey(K key) const;
/** STL-style iterators */
iterator begin();
const_iterator begin() const;
iterator end();
const_iterator end() const;
/** Raw data pointer access */
const T *Data() const;
T *Data(); // mutable version
/** Get vector data as span */
flatbuffers::span<const T> AsSpan() const;
};
// Utility functions
template<typename T>
uoffset_t VectorLength(const Vector<T> *v) {
return v ? v->size() : 0;
}
template<typename U>
flatbuffers::span<U> make_span(Vector<U> &vec) {
return flatbuffers::span<U>(vec.Data(), vec.size());
}FlatBuffer string class providing zero-copy string access with C++ standard library integration.
class String : public Vector<char> {
public:
/** Get null-terminated C-style string */
const char *c_str() const;
/** Get std::string copy */
std::string str() const;
/** Get string_view (C++17) */
std::string_view string_view() const;
/** Lexicographic comparison */
bool operator<(const String &o) const;
};
// Utility functions for safe string access
inline const char *GetCstring(const String *str) {
return str ? str->c_str() : nullptr;
}
inline std::string GetString(const String *str) {
return str ? str->str() : "";
}
inline std::string_view GetStringView(const String *str) {
return str ? str->string_view() : std::string_view();
}Base class for accessing FlatBuffer struct data stored inline without vtables.
class Struct {
public:
/** Get field at byte offset */
template<typename T>
T GetField(uoffset_t o) const;
/** Get nested struct at offset */
template<typename T>
T GetStruct(uoffset_t o) const;
/** Get field memory address */
const uint8_t *GetAddressOf(uoffset_t o) const;
};Global utility functions for working with FlatBuffer data and performing common operations.
/** Get buffer start from root pointer (reverse of GetRoot) */
inline const uint8_t *GetBufferStartFromRootPointer(const void *root);
/** Get prefixed buffer size */
template<typename SizeT = uoffset_t>
inline SizeT GetPrefixedSize(const uint8_t *buf);
/** Get total length including size prefix */
template<typename SizeT = uoffset_t>
inline SizeT GetSizePrefixedBufferLength(const uint8_t *const buf);
/** Test if field is present in generated table */
template<typename T>
bool IsFieldPresent(const T *table, typename T::FlatBuffersVTableOffset field);
/** Reverse lookup for enum names */
inline int LookupEnum(const char **names, const char *name);
/** Get FlatBuffers version string */
inline const char *flatbuffers_version_string();Core type definitions used throughout the FlatBuffers C++ API.
// Basic offset and size types
using uoffset_t = uint32_t; // Default 32-bit offset/size type
using uoffset64_t = uint64_t; // 64-bit offset type for large buffers
using soffset_t = int32_t; // Signed offset for bidirectional refs
using voffset_t = uint16_t; // VTable offset type
using largest_scalar_t = uintmax_t; // Largest scalar for alignment
// Template offset wrapper for type safety
template<typename T>
struct Offset {
uoffset_t o;
Offset() : o(0) {}
explicit Offset(uoffset_t offset) : o(offset) {}
};
// Optional type for fields that may not be present
template<typename T>
class Optional {
public:
Optional() : has_value_(false) {}
explicit Optional(T val) : has_value_(true), value_(val) {}
bool has_value() const { return has_value_; }
const T& value() const { return value_; }
T value_or(const T& default_value) const {
return has_value_ ? value_ : default_value;
}
};
// Constants
static const size_t kFileIdentifierLength = 4;
static const size_t FLATBUFFERS_MAX_BUFFER_SIZE = (1ULL << 31) - 1;
static const size_t FLATBUFFERS_MAX_ALIGNMENT = 32;Usage Example:
#include "example_generated.h" // Generated from schema
// Deserialize existing buffer
const uint8_t *buffer = /* ... buffer data ... */;
const Monster *monster = GetMonster(buffer);
// Access fields with zero-copy
std::cout << "Name: " << monster->name()->c_str() << std::endl;
std::cout << "HP: " << monster->hp() << std::endl;
// Access nested struct
if (monster->pos()) {
const Vec3 *pos = monster->pos();
std::cout << "Position: " << pos->x() << ", " << pos->y() << ", " << pos->z() << std::endl;
}
// Access vector data
if (monster->inventory()) {
const Vector<uint8_t> *inv = monster->inventory();
for (size_t i = 0; i < inv->size(); i++) {
std::cout << "Item " << i << ": " << inv->Get(i) << std::endl;
}
}