I would like to cast a vector<uint8_t>&
of binary data to a vector<int16_t>&
preferably without copying any data. Running the code below (compiled with gcc 9.4.0) I find that the size of data16
is 3. Is casting vector pointers with types of different sizes safe or does it produce undefined behaviour?
#include <cinttypes>
#include <iostream>
#include <vector>
int main()
{
std::vector<uint8_t> data8 = { 0, 0, 0, 0 };
std::vector<int16_t>& data16 = *reinterpret_cast<std::vector<int16_t>*>(&data8);
std::cout << data16.size() << std::endl;
}```