I use the STB library to load images into memory. The specific function, stbi_load
, returns a pointer to an unsigned char
, which is an array.
I'm tempted to use the new C++17 API for raw data, std::byte
, which would allow me to be more expressive, and let me alias the raw data pixel by pixel, or color by color by casting it to different data type (integers of different size).
Now I tried this:
std::unique_ptr<std::byte[], stbi_deleter>(stbi_load(...));
Of course it didn't work due to the lack of implicit conversion.
Then I tried that:
std::unique_ptr<std::byte[], stbi_deleter>(
static_cast<std::byte*>(stbi_load(...))
);
Again, it still didn't worked. I had to resolve to use reinterpret_cast
instead. And made me question whether this conversion is legal or not. Can I legally convert a unsigned char*
to std::byte*
according to the strict aliasing rule? And then can I cast the data to another datatype like std::uint32_t*
and mutate it? Will that also break the aliasing rule?