Advertisement
Ginsutime

Singletons Cherno Modern Example

Feb 16th, 2022
1,117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.56 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. class Random
  4. {
  5. public:
  6.     Random(const Random&) = delete;
  7.     // Might want to delete the assignment operator as well if making better
  8.  
  9.     // Can access any number of non-static methods using this.
  10.     static Random& Get() // This is the core of a singleton. Lifetime of it is same as that of the application.
  11.     {
  12.         // Static variable inside a function, still in static memory. Once Get called for first time, it'll be instantiated.
  13.         // On subsequent times, it'll be in static memory so it'll be referenced. Same as what we did before but cleaner.
  14.         static Random instance; // Replaces the 2 lines further down that we removed entirely
  15.         return instance;
  16.     }
  17.  
  18.     static float Float() { return Get().IFloat(); } // Return Get().IFloat(). Indirection. Lets you not have to do Random::Get().Float();
  19.     // Can also use do static float Float() { return Get().m_RandomGenerator; } if you don't need internal function at all
  20.     // Benefit of having internal function is that since it isn't static, it has access to all the class member without having to retrieve instance
  21.     // Can be used so that they map to private member functions instead of just using Get().
  22. private:
  23.     float IFloat() { return m_RandomGenerator; } // Internal Function that returns class member
  24.     Random() {}
  25.  
  26.     float m_RandomGenerator = 0.5f;
  27.  
  28.     // We remove static Random s_Instance; entirely
  29. };
  30.  
  31. // We remove Random Random::s_Instance; entirely
  32.  
  33. int main()
  34. {
  35.     float number = Random::Float(); // Used instead of Random::Get().Float();
  36.  
  37.     std::cout << number << std::endl;
  38.     std::cin.get();
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement