fork download
  1. #include <cassert>
  2. using namespace std;
  3.  
  4. class Box;
  5. class Rabbit {
  6. public:
  7. ~Rabbit() { disconnect(); }
  8. void connect(Box& box);
  9. void disconnect();
  10. Box* getMyBox() const { return box; }
  11. private:
  12. Box* box = nullptr;
  13. };
  14. class Box {
  15. public:
  16. ~Box() { disconnect(); }
  17. void connect(Rabbit& otherRabbit);
  18. void disconnect();
  19. Rabbit* getMyRabbit() const { return rabbit; }
  20. private:
  21. Rabbit* rabbit = nullptr;
  22. };
  23.  
  24. inline void Rabbit::connect(Box& otherBox)
  25. {
  26. if (box != &otherBox)
  27. {
  28. disconnect();
  29. box = &otherBox;
  30. box->connect(*this);
  31. }
  32. }
  33.  
  34. inline void Rabbit::disconnect()
  35. {
  36. if (box != nullptr)
  37. {
  38. Box* oldBox = box;
  39. box = nullptr; // do this before calling disconnect on box - otherwise you get infinite recursion...
  40. oldBox->disconnect();
  41. }
  42. }
  43.  
  44. inline void Box::connect(Rabbit& otherRabbit)
  45. {
  46. if (rabbit != &otherRabbit)
  47. {
  48. disconnect();
  49. rabbit = &otherRabbit;
  50. rabbit->connect(*this);
  51. }
  52. }
  53.  
  54. inline void Box::disconnect()
  55. {
  56. if (rabbit != nullptr)
  57. {
  58. Rabbit* oldRabbit = rabbit;
  59. rabbit = nullptr; // do this before calling disconnect on box - otherwise you get infinite recursion...
  60. oldRabbit->disconnect();
  61. }
  62. }
  63.  
  64. int main() {
  65. Box b1, b2;
  66. Rabbit r1;
  67.  
  68. b1.connect(r1);
  69. assert(b1.getMyRabbit() == &r1);
  70. assert(r1.getMyBox() == &b1);
  71.  
  72. r1.connect(b2);
  73. assert(b1.getMyRabbit() == nullptr);
  74. assert(r1.getMyBox() == &b2);
  75. assert(b2.getMyRabbit() == &r1);
  76.  
  77. b2.disconnect();
  78. assert(b1.getMyRabbit() == nullptr);
  79. assert(r1.getMyBox() == nullptr);
  80. assert(b2.getMyRabbit() == nullptr);
  81.  
  82. {
  83. Rabbit r2;
  84. r2.connect(b1);
  85. assert(b1.getMyRabbit() == &r2);
  86. assert(r2.getMyBox() == &b1);
  87. }
  88. assert(b1.getMyRabbit() == nullptr);
  89.  
  90.  
  91. }
Success #stdin #stdout 0s 3452KB
stdin
Standard input is empty
stdout
Standard output is empty