In C++, say you want to declare a global variable to be used by many. How do you do it?
I commonly use declare and define in cpp file, and then use extern in other cpp file (and not headers).
I don’t like this approach, and I am considering something along these lines:
In a header file:
some_file.h
Class MYGlobalClass { }; MyGlobalClass& MyGlobalClassInstance() { static MYGlobalClass instance; return instance; }
Edit
Consider in the following contexts:
- can be used in multi-threaded applications
- namespace pollution
- may NOT necessery be a singleton, as many instances of this might be created
What are your thoughts, suggestions, new ideas?
Declare it in one header file (using
extern), and define it in one.cpp(or whatever other extension) file. You may use a function and return a reference to a static variable like you showed to circumvent problems with construction order relative to other such namespace scope variables in other.cppfiles. But remember that won’t protect you from destruction order problems – which is in the exact reverse order from construction (these things are called ‘static initialization order fiasco’. If you use a function like yours and put it into headers, make it inline to make the redefinition of the function valid when it is included into multiple.cppfiles (logically, the function is still only apparent once, because the static in it will only exist once, not separately for each file it is included into). Alternatively just declare it in a header but define it in one.cppfile (but then, remove the inline from it!).The potential problems with destruction order can be circumvented by using
new:The destructor of it, however, will never be called then. If you need thread safety, you should add a mutex that protects against multiple accesses.
boost.threadprobably has something for that.