fork download
  1. #include <iostream>
  2. #include <memory>
  3.  
  4. class Controller;
  5.  
  6. class View {
  7. public:
  8. ~View() {
  9. std::cout << "Disposing View" << std::endl;
  10. }
  11.  
  12. void SetObserver(std::shared_ptr<Controller> a_observer) {
  13. observer = a_observer;
  14. }
  15. private:
  16. std::shared_ptr<Controller> observer;
  17. };
  18.  
  19. class Controller : public std::enable_shared_from_this<Controller> {
  20. public:
  21. static std::shared_ptr<Controller> Create(std::unique_ptr<View> view) {
  22. //Can't use std::make_shared due to visibility rules :(
  23. auto controller = std::shared_ptr<Controller>(new Controller(std::move(view)));
  24.  
  25. controller->Init();
  26.  
  27. return controller;
  28. }
  29.  
  30. ~Controller() {
  31. std::cout << "Disposing Controller" << std::endl;
  32. }
  33. private:
  34. std::unique_ptr<View> view;
  35.  
  36. explicit Controller(std::unique_ptr<View> a_view) : view(std::move(a_view)) {}
  37.  
  38. Controller(const Controller&) = delete;
  39.  
  40. void Init() {
  41. view->SetObserver(shared_from_this());
  42. }
  43. };
  44.  
  45. int main() {
  46. auto view = std::make_unique<View>();
  47.  
  48. auto controller = Controller::Create(std::move(view));
  49.  
  50. return 0;
  51. }
Success #stdin #stdout 0s 3412KB
stdin
Standard input is empty
stdout
Standard output is empty