I already read a lot of posts and articles all over the net, but I couldn't find a definite answer about this.
I have some functions with similar purposes that I want to have out of the global scope. Some of them need to be public, others should be private (because they are only helper functions for the "public" ones). Additionally, I don't have only functions, but also variables. They are only needed by the "private" helper functions and should be private, too.
Now there are the three ways:
What would be the way to take for me? Possible way of combining some of these ways?
I thought of something like:
Thanks.
While a static class is generally initialized when it is first loaded and it will lead to potential class loader issues. Singleton Objects stored on heap while static class stored in stack. Singleton Objects can have constructor while Static Class cannot.
The static instance variable inside of a singleton is meant to hold the only instance of the class that will exist. It is static because it will need to be referenced by a static method 'GetInstance()' that will return the instance, or will create the instance if it is the first time that 'GetInstance()' was called.
Statics are the metter of classes --> no relation with singleton pattern.
As noted, using global variables is generally bad engineering practice, unless absolutely needed of course (mapping hardware for example, but that doesn't happen THAT often).
Stashing everything in a class is something you would do in a Java-like language, but in C++ you don't have to, and in fact using namespaces here is a superior alternative, if only:
Here is a typical implementation:
// foo.h #ifndef MYPROJECT_FOO_H_INCLUDED #define MYPROJECT_FOO_H_INCLUDED namespace myproject { void foo(); void foomore(); } #endif // MYPROJECT_FOO_H_INCLUDED // foo.cpp #include "myproject/foo.h" namespace myproject { namespace { typedef XXXX MyHelperType; void bar(MyHelperType& helper); } // anonymous void foo() { MyHelperType helper = /**/; bar(helper); } void foomore() { MyHelperType helper = /**/; bar(helper); bar(helper); } } // myproject
The anonymous namespace neatly tucked in a source file is an enhanced private
section: not only the client cannot use what's inside, but he does not even see it at all (since it's in the source file) and thus do not depend on it (which has definite ABI and compile-time advantages!)
Don't make it a singleton
For public helper functions that don't directly depend on these variables, make them non-member functions. There's nothing gained by putting them in a class.
For the rest, put it in a class as normal non-static members. If you need a single globally accessible instance of the class, then create one (but don't make it a singleton, just a global).
Otherwise, instantiate it when needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With