mercredi 20 mai 2020

Manipulating byte vector through float pointer

Is it possible to manipulate an std::vector<unsigned char> through its data pointer as if it were a container of float?

Here is an example that compiles and (seemingly?) runs as desired (GCC 4.8, C++11):

#include <iostream>
#include <vector>

int main()
{
    std::vector<unsigned char> bytes(2 * sizeof(float));
    auto ptr = reinterpret_cast<float *>(bytes.data());
    ptr[0] = 1.1;
    ptr[1] = 1.2;
    std::cout << ptr[0] << ", " << ptr[1] << std::endl;
    return 0;
}

This snippet successfully writes/reads data from the byte buffer as if it were an array of float. From reading about reinterpret_cast I'm afraid that this might be undefined behavior. My confidence in understanding the type aliasing details is too little for me to be sure.

Is the code snippet undefined behavior as outlined above? If so, is there another way to achieve this sort of byte manipulation?

Aucun commentaire:

Enregistrer un commentaire