cppcoreguidelines-pro-type-union-access

According to https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Ru-pun using union for type-punning is undefined behaviour.
  See also https://en.wikipedia.org/wiki/Type_punning#Use_of_union. Replace it with std::memcpy.
This commit is contained in:
wmayer
2022-06-25 17:17:04 +02:00
parent 14668197d1
commit 7de296b60e
2 changed files with 42 additions and 30 deletions

View File

@@ -1097,15 +1097,11 @@ void PcdReader::read(const std::string& filename)
}
}
else if (types[rgba] == "F") {
union RGBA {
uint32_t u;
float f;
};
union RGBA v;
static_assert(sizeof(float) == sizeof(uint32_t), "float and uint32_t have different sizes");
for (std::size_t i=0; i<numPoints; i++) {
v.f = static_cast<float>(data(i,rgba));
uint32_t packed = v.u;
float f = static_cast<float>(data(i,rgba));
uint32_t packed;
std::memcpy(&packed, &f, sizeof(packed));
uint32_t a = (packed >> 24) & 0xff;
uint32_t r = (packed >> 16) & 0xff;
uint32_t g = (packed >> 8) & 0xff;