[C++] Fix -Wnarrowing and -Woverflow due to signed bitfields on G++ ARM (#6163)

Older versions of GCC (at least on ARM) complain about narrowing conversions and
overflows when setting the reference index (defined as an 11-bit signed integer
bitfield) to -1:

```
error: narrowing conversion of '-1' from 'int' to 'short unsigned int' inside { } [-Wnarrowing]
error: conversion from 'short unsigned int' to 'short unsigned int:11' changes value from '65535' to '2047'
```

This is due to the signedness of integer bitfields (not explicitly signed or
unsigned) being implementation-defined. This addresses this issue by explicitly
defining the signedness of all the bitfields in `flatbuffers::TypeCode` in C++.
This commit is contained in:
Anass Al
2020-10-08 08:00:40 -07:00
committed by GitHub
parent 7b9e61fccf
commit cb971eece8

View File

@@ -2745,10 +2745,13 @@ inline const char * const *ElementaryTypeNames() {
// clang-format on
// Basic type info cost just 16bits per field!
// We're explicitly defining the signedness since the signedness of integer
// bitfields is otherwise implementation-defined and causes warnings on older
// GCC compilers.
struct TypeCode {
uint16_t base_type : 4; // ElementaryType
uint16_t is_repeating : 1; // Either vector (in table) or array (in struct)
int16_t sequence_ref : 11; // Index into type_refs below, or -1 for none.
unsigned short base_type : 4; // ElementaryType
unsigned short is_repeating : 1; // Either vector (in table) or array (in struct)
signed short sequence_ref : 11; // Index into type_refs below, or -1 for none.
};
static_assert(sizeof(TypeCode) == 2, "TypeCode");