I have two questions, a general one about pointer type-manipulation in general, and then one for a specific case I have.
What happens when you access a buffer of memory using pointers of different types?
In practice on many different compilers, it seems to work out as my brain would like to envision it. However, I sort-of know it's UB in many (if not all cases). For example:
typedef unsigned char byte;
struct color { /* stuff */};
std::vector<color> colors( 512 * 512 );
// pointer of one type
color* colordata = colors.data();
// pointer to another type?
byte* bytes = reinterpret_cast<byte*>( colordata );
// Proceed to read from (potentially write into)
// the "bytes" of the 512 * 512 heap array
The first question would be: Is there any point where doing this kind of conversion is legal/safe/standard-sanctioned?
The second question: spinning off the first, if you knew that the struct
named color
was defined as:
struct color { byte c[4]; };
Now, is it legal/safe/standard-sactioned? Read-safe? Read / Write safe? I'd like to know, as my intuition tells me that for these very simple structs, the above naughty pointer manipulation isn't that bad, or is it?
[ Reopen Reasons: ] While the linked question about strict aliasing applies somewhat here, it is mostly about C. The one answer referencing the C++03 standard may be outdated when compared to the C++11 standard (unless absolutely nothing has changed). This question has a practical application and I and others would benefit from more answers. Finally, this question is very specific in asking whether it is not only read-safe, write-safe, or both (or neither, and in two different scenarios (PoD data where the underlying types match and a more general case of arbitrary internal data).