Guest User

Untitled

a guest
Dec 11th, 2017
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. class GlobalClass
  4. {
  5. int m_value;
  6. static GlobalClass *s_instance;
  7. GlobalClass(int v = 0){
  8. std::cout << "global singleton being born at " << this << std::endl;
  9. m_value = v;
  10. };
  11. ~GlobalClass(){
  12. std::cout << "global singleton being killed at " << this << std::endl;
  13. };
  14. public:
  15. int get_value()
  16. {
  17. return m_value;
  18. }
  19. void set_value(int v)
  20. {
  21. m_value = v;
  22. }
  23. void kill_me(){
  24. std::cout << "global singleton is dying!" << std::endl;
  25. delete this;
  26. }
  27. static GlobalClass *instance()
  28. {
  29. if (!s_instance)
  30. s_instance = new GlobalClass;
  31. return s_instance;
  32. }
  33. };
  34.  
  35. // Allocating and initializing GlobalClass's
  36. // static data member. The pointer is being
  37. // allocated - not the object inself.
  38. GlobalClass *GlobalClass::s_instance = nullptr;
  39.  
  40. class accessor {
  41. public:
  42. accessor(int _id) : id(_id){std::cout << "birthing accessor: " << id << std::endl;};
  43. ~accessor(){std::cout << "killing accessor: " << id << std::endl;};
  44.  
  45. void get_par(){
  46. std::cout << "im accessing the global thing " << GlobalClass::instance()->get_value() << std::endl;
  47. };
  48. private:
  49. int id;
  50. };
  51.  
  52. void foo(void)
  53. {
  54. std::cout << "entering foo" << std::endl;
  55. std::cout << "foo: global_ptr is " << GlobalClass::instance()->get_value() << '\n';
  56. GlobalClass::instance()->set_value(1);
  57. std::cout << "foo: global_ptr is " << GlobalClass::instance()->get_value() << '\n';
  58. std::cout << "exiting foo" << std::endl;
  59. }
  60.  
  61. void bar(void)
  62. {
  63. std::cout << "entering bar" << std::endl;
  64. std::cout << "bar: global_ptr is " << GlobalClass::instance()->get_value() << '\n';
  65. GlobalClass::instance()->set_value(2);
  66. std::cout << "bar: global_ptr is " << GlobalClass::instance()->get_value() << '\n';
  67. std::cout << "exiting bar" << std::endl;
  68. }
  69.  
  70. int main()
  71. {
  72. std::cout << "main: global_ptr is " << GlobalClass::instance()->get_value() << std::endl;
  73.  
  74. GlobalClass::instance()->set_value(5);
  75.  
  76. accessor* accessor1 = new accessor(1);
  77. accessor1->get_par();
  78.  
  79. foo();
  80. bar();
  81. delete accessor1;
  82. std::cout << "main: global_ptr is " << GlobalClass::instance()->get_value() << std::endl;
  83. GlobalClass::instance()->kill_me();
  84. }
Add Comment
Please, Sign In to add comment