fork download
  1. #include <iostream>
  2. #include <cstdint>
  3. #include <algorithm>
  4. using namespace std;
  5.  
  6. union structA{
  7. uint8_t mem[3];
  8.  
  9. struct{
  10. unsigned field1 : 8;
  11. unsigned field2 : 12;
  12. unsigned field3 : 4;
  13. };
  14. };
  15.  
  16. struct structB{
  17. uint8_t mem[10];
  18. };
  19.  
  20.  
  21. int main() {
  22.  
  23. cout << "Infos:"<<endl;
  24. cout << " Alignment constraint of structA: "<<alignof(structA)<<endl;
  25. cout << " Alignment constraint of uint8_t: "<<alignof(uint8_t)<<endl;
  26. cout << " Size : "<<sizeof(structA)<<endl;
  27. cout << " Is trivially copyable: "<<is_trivially_copyable<structA>::value<<endl;
  28.  
  29. structA ia; // test object
  30. ia.field1 =7; ia.field2=911; ia.field3=5;
  31.  
  32. uint8_t globalMem[128];
  33. fill( globalMem, globalMem +sizeof(globalMem), 0);
  34.  
  35. structA *pa = new (globalMem+10) structA(ia); // placement new to properly create object
  36.  
  37. structA a1 = *reinterpret_cast<structA*>(&globalMem[0]);
  38. structA a2 = *reinterpret_cast<structA*>(&globalMem[10]);
  39. structB b1 = *reinterpret_cast<structB*>(&globalMem[30]);
  40.  
  41. cout <<endl<<"Test:"<<endl;
  42. cout << " original: "<<ia.field1<<" "<<ia.field2<<" "<<ia.field3<<endl;
  43. cout << " copy: " <<a2.field1<<" "<<a2.field2<<" "<<a2.field3<<endl;
  44.  
  45. return 0;
  46. }
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
Infos:
  Alignment constraint of structA: 4
  Alignment constraint of uint8_t: 1
  Size : 4
  Is trivially copyable: 1

Test:
  original: 7 911 5
  copy:     7 911 5