Global variables in C ++

In a multi-threaded C ++ application with many classes, I'm trying to figure out which methods define a global variable

  • C, define it as global in any source file, define it as extern in the header, which is included in the classes that access this variable.

  • Write a Singleton class that contains these global variables and provides set / get methods for writing to a variable.

In the second method, you can manage multi-threaded access through locks in a centralized manner, rather than the first approach.

Are there any better ways?

+5
source share
9 answers

" " ( - ?), . (, , ), get/put accessors.

+3

. (, cin, cout cerr), , , ( ) .

+4

Singleton. "" .

+3

( ?), , . - , .

+1

.

++ ::, .

:: variable-name;

vriable.

+1

, , , , .

-, , , . . , .

-, , . , . , , .

, .

+1

.

C , Singleton:: instance(). Singleton:: instance() .

, C-, Schwarz Counter. http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Nifty_Counter

0

, handle/body.

" ++" singleton MT .

0

Not kicking a dead horse, but, as already mentioned, avoiding globals is the best solution. Some reasons are listed here . If a global variable is required, you can consider providing a function for its access to avoid the so-called "global initialization fiasco."

0
source

All Articles