6

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.

Community
  • 1
  • 1
sandthorn
  • 2,770
  • 1
  • 15
  • 59
  • 3
    because, in general, it violates strict aliasing rules ? – Massimiliano Janes Dec 21 '17 at 13:56
  • 2
    this was already asked here: https://stackoverflow.com/questions/47924103/pointer-interconvertibility-vs-having-the-same-address – underscore_d Dec 21 '17 at 14:03
  • If you thing an Array is *just* a Pointer, try to compare `sizeof(carr)` and `sizeof(ch0)`. I am not sure about why it works between aclass and its first member though. – Vulpo Dec 21 '17 at 14:49

0 Answers0