What is the best way to declare a global variable?

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?

+5
source share
8 answers

( extern) .cpp ( ). , , .cpp. , , ( " ". ​​, , , , .cpp (, , , , ). , .cpp ( !).

inline A& getA() { static A a; return a; }

, new:

inline A& getA() { static A *a = new A; return *a; }

, , . , , . boost.thread , - .

+2

, , " ". , . , " " - , , . .

"" ++. , , , , , - , .

, , , .

- . , , , , , .

+10

extern , "many", *.cpp

+4

. , , , . , MyGlobalClassInstance ? , , ++, MyGlobalClass, , .

, , .

, , , , main, .

+2

cpp

extern -ed . .

. .

namespace myns {
   int foo = 0;
}

, , Singletion. , Singleton. , , inline - ODR .

+1

, , extern :

// MyClass.h
class MyClass { ... };
extern MyClass myGlobalInstance;

// MyClass.cpp
MyClass myGlobalInstance;

, , , ( ) , ( ), :

1:

// MyClass.h
class MyClass
{
private:  // or protected, if you want it accessible by subclasses
    static MyClass myGlobalInstance;
};

2:

// MyClass.cpp
void someFunction()
{
    // it global, but only accessible inside this function
    static MyClass myGlobalInstance;
    ...
}

3:

// MyClass.cpp
namespace
{
    MyClass myGlobalInstance;
}

// it now only accessible in this file
+1

extern MyGlobalClass MyGlobalClassInstance;

: > . <

0

singleton?

-1

All Articles