FlatBuffers中VectorLength返回size_t而Vector::size返回uoffset_t的原因是什么
FlatBuffers Vector长度类型不匹配问题
该类型差异有时会在64位编译场景下引发问题。若没有特殊的设计考量,建议为VectorLength()和Vector::size()统一索引类型。
如下示例中,调用print_first_n_of_inventory时传入VectorLength的返回值就需要做强制类型转换:
#include <flatbuffers/flatbuffers.h> #include <tests/monster_test_generated.h> #include <iostream> using namespace flatbuffers; using namespace MyGame::Example; void print_first_n_of_inventory(const Vector<uint8_t> * pInventory, uoffset_t n) { for (uoffset_t i = 0; i < n; ++i) { auto val = pInventory->Get(i); std::cout << val << "\n"; } } int main(int, char * argv[]) { auto * pMonster = GetMonster(argv[1]); auto * pInventory = pMonster->inventory(); print_first_n_of_inventory(pInventory, 2); print_first_n_of_inventory(pInventory, pInventory->size()); // warning C4267: 'argument': conversion from 'size_t' to 'flatbuffers::uoffset_t', possible loss of data print_first_n_of_inventory(pInventory, VectorLength(pInventory)); return 0; }
当前调用VectorLength时会触发C4267编译告警,提示存在size_t到uoffset_t转换的数据丢失风险。
内容的提问来源于stack exchange,提问作者Stefan F.
相关产品推荐
相关产品推荐

