fork download
  1. #include <vector>
  2. #include <iostream>
  3. #include <assert.h>
  4. #include <inttypes.h>
  5. #include <stddef.h>
  6. #include <memory.h>
  7.  
  8. struct MyStandardLayout {
  9. char mem_a;
  10. int16_t num_1;
  11. int32_t num_2;
  12. int64_t num_3;
  13. char mem_z;
  14.  
  15. MyStandardLayout()
  16. : mem_a('a')
  17. , num_1(1)
  18. , num_2(2)
  19. , num_3(3)
  20. , mem_z('z')
  21. { }
  22.  
  23. void print() const {
  24. std::cout <<
  25. "MySL Obj: " <<
  26. mem_a << " / " <<
  27. num_1 << " / " <<
  28. num_2 << " / " <<
  29. num_3 << " / " <<
  30. mem_z << "\n";
  31. }
  32. };
  33.  
  34. void ZeroInts(MyStandardLayout* pObj) {
  35. void* const pFirst = static_cast<void*>(&pObj->num_1);
  36. void* const pLast = static_cast<void*>(&pObj->num_3);
  37.  
  38. const ptrdiff_t delta = static_cast<char*>(pLast) - static_cast<char*>(pFirst);
  39. assert(delta > 0);
  40. std::cout << "delta = " << delta << "\n";
  41. const size_t sizeAll = delta + sizeof(int);
  42. std::cout << "sizeAll = " << sizeAll << "\n";
  43.  
  44. std::vector<char> buf( sizeAll, 0 );
  45. memcpy(pFirst, &buf[0], sizeAll);
  46. }
  47.  
  48. int main()
  49. {
  50. MyStandardLayout obj;
  51. obj.print();
  52. ZeroInts(&obj);
  53. obj.print();
  54.  
  55. return 0;
  56. }
  57.  
  58.  
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
MySL Obj: a / 1 / 2 / 3 / z
delta =  6
sizeAll =  10
MySL Obj: a / 0 / 0 / 0 / z