fork(2) 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. size_t index;
  13. int a[4];
  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(2));
  53. vec.push_back(make_record(4));
  54. vec.push_back(make_record(8));
  55.  
  56. for(auto b : vec)
  57. b->print();
  58. }
  59.  
Success #stdin #stdout 0s 3428KB
stdin
Standard input is empty
stdout
B has 2 As
A[0]
A[1]
B has 4 As
A[0]
A[1]
A[2]
A[3]
B has 8 As
A[0]
A[1]
A[2]
A[3]
A[4]
A[5]
A[6]
A[7]