In C ++, say you want to declare a global variable that will be used by many. How do you do this?
I usually use declare and define in the cpp file and then use extern in another cpp file (and not in the headers).
I do not like this approach, and I am considering something in this direction:
In the header file:
some_file.h
Class MYGlobalClass
{
};
MyGlobalClass& MyGlobalClassInstance()
{
static MYGlobalClass instance;
return instance;
}
Edit
Consider the following contexts:
- can be used in multi-threaded applications
- namespace pollution
- Can NOT be single line, as many instances of this can be created
What are your thoughts, suggestions, new ideas?
Sasha
source
share