I read that it's a good idea to keep the number of globals in your project as low as possible.
now what would be good ways to avoid global variables?
I read that it's a good idea to keep the number of globals in your project as low as possible.
now what would be good ways to avoid global variables?
Have a search for the "Singleton" pattern
Make use of function parameters, passing by (const) reference, or passing pointers, if necessary.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
It is a perfectly legit pattern and is also in the gang of four design patterns book. There are times, like any other pattern, where it is used when another pattern would work just as well. However, I would not claim singleton is a bad design pattern.Is this really much better than globals?
It's also sometimes known as the anti-pattern by people who don't like it.
It has been criticized by experts too, IIRC.
Fortunately said experts don't see my code so I could care less. Exclusionary thinkers annoy me to no end.It has been criticized by experts too, IIRC.
If we return to the context of the original question:
There are several reasons for this, and some of them have to do with avoiding global state, e.g., it may be more difficult to reason about the program and reusability may be impaired. In such cases, applying the singleton pattern to get rid of a global variable does not actually make an improvement. On the other hand, if the global variable is supposed to be a singleton, then applying the singleton pattern to enforce this makes sense.Originally Posted by FpaFtw
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
>>In such cases, applying the singleton pattern to get rid of a global variable does not actually make an improvement. On the other hand, if the global variable is supposed to be a singleton, then applying the singleton pattern to enforce this makes sense.
That's actually a good point.