fork(1) download
  1. #include <iostream>
  2. #include <memory>
  3.  
  4. class trigger
  5. {
  6. public:
  7. trigger() : m_flag(true) {}
  8. bool get() const { return m_flag; }
  9.  
  10. friend class trackable;
  11.  
  12. private:
  13. void set(bool flag) { m_flag = flag; }
  14. bool m_flag;
  15. };
  16.  
  17. typedef std::shared_ptr<trigger> spy_type;
  18.  
  19. class trackable
  20. {
  21. public:
  22. trackable(const trackable &)
  23. : spy(std::make_shared<trigger>())
  24. {}
  25.  
  26. trackable()
  27. : spy(std::make_shared<trigger>())
  28. {}
  29.  
  30. trackable &operator=(const trackable &) { return *this; }
  31.  
  32. ~trackable() { spy->set(false); }
  33. spy_type spy;
  34. };
  35.  
  36.  
  37. struct SomeObject : public trackable
  38. {
  39. //...
  40. };
  41.  
  42. struct SomeClient
  43. {
  44. SomeObject * m_Object;
  45.  
  46. bool objectIsValid() const { return (spy) ? spy->get() : false; }
  47.  
  48. void setObject(SomeObject * obj)
  49. {
  50. m_Object = obj;
  51. spy = obj->spy;
  52. }
  53.  
  54. private:
  55. spy_type spy;
  56. };
  57.  
  58.  
  59. int main()
  60. {
  61. SomeClient Client;
  62.  
  63. std::cout << std::boolalpha << Client.objectIsValid() << std::endl;
  64.  
  65. SomeObject * Object = new SomeObject();
  66.  
  67. Client.setObject(Object);
  68.  
  69. std::cout << Client.objectIsValid() << std::endl;
  70.  
  71. delete Object;
  72.  
  73. std::cout << Client.objectIsValid() << std::endl;
  74.  
  75. return 0;
  76. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
false
true
false