fork(1) download
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. class A;
  5. class B;
  6.  
  7. // a buffer contains array of A followed by B
  8. // | A[N - 1]...A[0] | B |
  9.  
  10. class A
  11. {
  12. unsigned char index;
  13. unsigned char a;
  14. public:
  15. A(size_t index) : index(index) {}
  16. const B* getB() const { return reinterpret_cast<const B*>(this + index + 1); }
  17. void print() const { std::cout << "A[" << index << "]\n"; }
  18. };
  19.  
  20. class B
  21. {
  22. size_t a_count;
  23. int b[16];
  24. public:
  25. virtual ~B() {}
  26. B(size_t a_count) : a_count(a_count) {}
  27. const A* getA(size_t i) const { return reinterpret_cast<const A*>(this) - i - 1; }
  28. void print() const
  29. {
  30. std::cout << "B has " << a_count << " As\n";
  31. for(auto i = 0; i < a_count; ++i)
  32. {
  33. getA(i)->print();
  34. }
  35. }
  36. };
  37.  
  38. B* make_record(size_t a_count)
  39. {
  40. char* buf = new char[a_count*sizeof(A) + sizeof(B)];
  41. for(auto i = 0; i < a_count; ++i)
  42. {
  43. new(buf) A(a_count - i - 1);
  44. buf += sizeof(A);
  45. }
  46. return new(buf) B(a_count);
  47. }
  48.  
  49. int main()
  50. {
  51. std::vector<B*> vec;
  52. vec.push_back(make_record(0));
  53. vec.push_back(make_record(1));
  54. vec.push_back(make_record(2));
  55.  
  56. for(auto b : vec) {
  57. std::cout << "B starts at " << b << ", needs alignment " << alignof(B)
  58. << ", misaligned by " << (reinterpret_cast<uintptr_t>(b) % alignof(B)) << std::endl;
  59. b->print();
  60. }
  61. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
B starts at 0x9003008, needs alignment 4, misaligned by 0
B has 0 As
B starts at 0x900306a, needs alignment 4, misaligned by 2
B has 1 As
A[]
B starts at 0x90030cc, needs alignment 4, misaligned by 0
B has 2 As
A[]
A[]