fork download
  1. #include <iostream>
  2.  
  3. template <typename T>
  4. class global_ptr
  5. {
  6. public:
  7. T* get()
  8. {
  9. return &get_instance();
  10. }
  11.  
  12. T* operator->()
  13. {
  14. return get();
  15. }
  16.  
  17. T& operator*()
  18. {
  19. return *get();
  20. }
  21.  
  22. // could add const overloads, so clients can
  23. // differentiate between read-only and read/write
  24. // access, for smarter mutex locking (shared)
  25.  
  26. private:
  27. static T& get_instance()
  28. {
  29. static T result;
  30. return result;
  31. }
  32. };
  33.  
  34. typedef global_ptr<int> global_int;
  35.  
  36. void foo()
  37. {
  38. // all instances of this actually refer to the same global object
  39. global_int gi;
  40. *gi = 5;
  41.  
  42. std::cout << *gi << std::endl;
  43. }
  44.  
  45. void bar()
  46. {
  47. global_int gi;
  48. *gi = 7;
  49.  
  50. std::cout << *gi << std::endl;
  51. }
  52.  
  53. int main()
  54. {
  55. // not created until first use
  56. foo();
  57. bar();
  58.  
  59. global_int gi;
  60. *gi = 11;
  61.  
  62. std::cout << *gi << std::endl;
  63. }
  64.  
  65. // could be extended, now, to support destruction policies, etc.
Success #stdin #stdout 0s 2828KB
stdin
Standard input is empty
stdout
5
7
11