Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- class Random
- {
- public:
- Random(const Random&) = delete;
- // Might want to delete the assignment operator as well if making better
- // Can access any number of non-static methods using this.
- static Random& Get() // This is the core of a singleton. Lifetime of it is same as that of the application.
- {
- // Static variable inside a function, still in static memory. Once Get called for first time, it'll be instantiated.
- // On subsequent times, it'll be in static memory so it'll be referenced. Same as what we did before but cleaner.
- static Random instance; // Replaces the 2 lines further down that we removed entirely
- return instance;
- }
- static float Float() { return Get().IFloat(); } // Return Get().IFloat(). Indirection. Lets you not have to do Random::Get().Float();
- // Can also use do static float Float() { return Get().m_RandomGenerator; } if you don't need internal function at all
- // 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
- // Can be used so that they map to private member functions instead of just using Get().
- private:
- float IFloat() { return m_RandomGenerator; } // Internal Function that returns class member
- Random() {}
- float m_RandomGenerator = 0.5f;
- // We remove static Random s_Instance; entirely
- };
- // We remove Random Random::s_Instance; entirely
- int main()
- {
- float number = Random::Float(); // Used instead of Random::Get().Float();
- std::cout << number << std::endl;
- std::cin.get();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement