Actual use of reinterpret_cast?

Empirically the following works (gcc and VC ++), but is it valid and portable code?

typedef struct { int w[2]; } A; struct B { int blah[2]; }; void my_func(B b) { using namespace std; cout << b.blah[0] << b.blah[1] << endl; } int main(int argc, char* argv[]) { using namespace std; A a; aw[0] = 1; aw[1] = 2; cout << aw[0] << aw[1] << endl; // my_func(a); // compiler error, as expected my_func(reinterpret_cast<B&>(a)); // reinterpret, magic? my_func( *(B*)(&a) ); // is this equivalent? return 0; } // Output: // 12 // 12 // 12 
  • Is reinterpret_cast valid?
  • Is the cast equivalent of the C-style?
  • If the intention is for the bits located in &a be interpreted as type B, is this the correct / best approach?

(Off topic: for those who want to know why I'm trying to do this, I am dealing with two C libraries that want 128 bits of memory and use structures with different internal names - similar to structures in my example. I do not need memcopy, and I don’t want to crack in third-party code.)

+2
c ++
source share
1 answer

In C ++ 11, this is fully permitted if the two types are compatible with layouts, which is true for structures that are identical and have a standard layout. See this answer for more details .

You can also insert two structures in the same union in previous versions of C ++, which had some guarantees about the possibility of access to identical data elements ("common initial sequence" of data elements) in the same order for another structure types.

In this case, yes, a C-style cast is equivalent, but reinterpret_cast is probably more idiomatic.

+2
source share

All Articles