Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // valid: type -> char
- int i = 0;
- char * c = reinterpret_cast<char*>(&i);
- // valid: char -> type
- char c[sizeof(int)]; // EDIT: alignment issue, see update below
- int * i = reinterpret_cast<int*>(c);
- // valid? char -> type1 and char -> type2
- char c[sizeof(uint32_t)];
- uint32_t * i = reinterpret_cast<uint32_t*>(c);
- uint16_t * s = reinterpret_cast<uint16_t*>(c);
- // valid: char -> type
- char c[sizeof(int)];
- int * i = reinterpret_cast<int*>(c);
- struct alignas(sizeof(int)) aligned { char c[sizeof(int)]; };
- aligned a;
- int * i = reinterpret_cast<int*>(a.c);
- alignas(int) char c[sizeof(int)];
- std::aligned_storage<sizeof(int), alignof(int)>::type c;
- // assume constexpr max
- constexpr auto alignment = max(alignof(int), alignof(short));
- alignas(alignment) char c[sizeof(int)];
- // I'm assuming here that the OP really meant to use &c and not c
- // this is, however, inconsequential
- auto p = magic_cast<int*>(&c);
- *p = 42;
- *magic_cast<short*>(p) = 42;
- // alignment same as before
- alignas(alignment) char c[sizeof(int)];
- auto p = magic_cast<int*>(&c);
- // end lifetime of c
- c.~decltype(c)();
- // reuse storage to construct new int object
- new (&c) int;
- *p = 42;
- auto q = magic_cast<short*>(p);
- // end lifetime of int object
- p->~decltype(0)();
- // reuse storage again
- new (p) short;
- *q = 42;
- alignas(alignment) char c[sizeof(int)];
- *magic_cast<int*>(&c) = 42;
- *magic_cast<short*>(&c) = 42;
- // valid: char -> type
- alignas(int) char c[sizeof(int)];
- int * i = reinterpret_cast<int*>(c);
- alignas(int) char c[sizeof(int)];
- int * i = reinterpret_cast<int*>(c);
- void foo( char* );
- alignas(int) char c[sizeof( int )];
- foo( c );
- int* p = reinterpret_cast<int*>( c );
- cout << *p << endl;
Add Comment
Please, Sign In to add comment