Guest User

Untitled

a guest
Jan 19th, 2019
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. // valid: type -> char
  2. int i = 0;
  3. char * c = reinterpret_cast<char*>(&i);
  4.  
  5. // valid: char -> type
  6. char c[sizeof(int)]; // EDIT: alignment issue, see update below
  7. int * i = reinterpret_cast<int*>(c);
  8.  
  9. // valid? char -> type1 and char -> type2
  10. char c[sizeof(uint32_t)];
  11. uint32_t * i = reinterpret_cast<uint32_t*>(c);
  12. uint16_t * s = reinterpret_cast<uint16_t*>(c);
  13.  
  14. // valid: char -> type
  15. char c[sizeof(int)];
  16. int * i = reinterpret_cast<int*>(c);
  17.  
  18. struct alignas(sizeof(int)) aligned { char c[sizeof(int)]; };
  19. aligned a;
  20. int * i = reinterpret_cast<int*>(a.c);
  21.  
  22. alignas(int) char c[sizeof(int)];
  23.  
  24. std::aligned_storage<sizeof(int), alignof(int)>::type c;
  25.  
  26. // assume constexpr max
  27. constexpr auto alignment = max(alignof(int), alignof(short));
  28. alignas(alignment) char c[sizeof(int)];
  29. // I'm assuming here that the OP really meant to use &c and not c
  30. // this is, however, inconsequential
  31. auto p = magic_cast<int*>(&c);
  32. *p = 42;
  33. *magic_cast<short*>(p) = 42;
  34.  
  35. // alignment same as before
  36. alignas(alignment) char c[sizeof(int)];
  37.  
  38. auto p = magic_cast<int*>(&c);
  39. // end lifetime of c
  40. c.~decltype(c)();
  41. // reuse storage to construct new int object
  42. new (&c) int;
  43.  
  44. *p = 42;
  45.  
  46. auto q = magic_cast<short*>(p);
  47. // end lifetime of int object
  48. p->~decltype(0)();
  49. // reuse storage again
  50. new (p) short;
  51.  
  52. *q = 42;
  53.  
  54. alignas(alignment) char c[sizeof(int)];
  55. *magic_cast<int*>(&c) = 42;
  56. *magic_cast<short*>(&c) = 42;
  57.  
  58. // valid: char -> type
  59. alignas(int) char c[sizeof(int)];
  60. int * i = reinterpret_cast<int*>(c);
  61.  
  62. alignas(int) char c[sizeof(int)];
  63. int * i = reinterpret_cast<int*>(c);
  64.  
  65. void foo( char* );
  66.  
  67. alignas(int) char c[sizeof( int )];
  68.  
  69. foo( c );
  70. int* p = reinterpret_cast<int*>( c );
  71. cout << *p << endl;
Add Comment
Please, Sign In to add comment