According to this
http://eel.is/c++draft/basic.compound#4
Two objects a and b are pointer-interconvertible if:
- they are the same object, or
- one is a union object and the other is a non-static data member of that object ([class.union]), or
- one is a standard-layout class object and the other is the first non-static data member of that object, or, if the object has no non-static data members, the first base class subobject of that object ([class.mem]), or
- there exists an object c such that a and c are pointer-interconvertible, and c and b are pointer-interconvertible.
If two objects are pointer-interconvertible, then they have the same address, and it is possible to obtain a pointer to one from a pointer to the other via a reinterpret_cast. [ Note: An array object and its first element are not pointer-interconvertible, even though they have the same address. — end note ]
Why do c++ standard not guarantee pointer-interconvertibility between an array of objects and its first element whereas do guarantee class and its 1st member ?
How come this is undefined behavior?
char carr[8];
char& ch0 = carr[0];
auto& carr2 = reinterpret_cat<char (&) [8]>(ch0); // Is this considered undefined behavior?
// Because ch0 (char&) and carr2 (char(&)[8]) are not "pointer-interconvertible".
// So they can not use reinterpret_cast "definedly".
// Array and its first element are not "pointer-interconvertible"
// eventhough they share the same address.
While this is an example on the standard itself.
http://www.eel.is/c++draft/basic.types#2
#define N sizeof(T)
char buf[N];
T obj; // obj initialized to its original value
std::memcpy(buf, &obj, N); // between these two calls to std::memcpy,
// obj might be modified
std::memcpy(&obj, buf, N); // at this point, each subobject of obj
// of scalar type holds its original value
Think if T = char[N]? Well, wouldn't &obj become char(&)[N]? Why is std::memcpy so superior that it can use char(&)[N] while we can't.
This is so amusing.
I'm eager to know why the standard intentionally make char *
and std::memcpy
only tools to iterate storage by bytes.