1. local variable
change lifetime, keep scope
move the var stored in stack to static/global area, so during compile it will have a memory address, and memory address keeps live until program ends. But scope keep the same, eg. inside counter(), it always work only inside counter().
void counter() { int normal_var = 0; // Created and destroyed on EVERY call static int static_var = 0; // Created ONCE, stays in memory forever normal_var++; static_var++; std::cout << "Normal: " << normal_var << " | Static: " << static_var << "\n"; } int main() { counter(); // Normal: 1 | Static: 1 counter(); // Normal: 1 | Static: 2 counter(); // Normal: 1 | Static: 3 return 0; } we can share the local var by its static address, which means return the address (pointer or reference), but this is bad practice(Broken Encapsulation and thread safety). except one case, Meyer's Singleton -- uses a function-local static variable to create a single instance on first use. (see below 4.2 magic statics)
2. static inside class
- static class members -- shared across instance, but init outside calss (C++17 can use
inline staticfor init) - static class function
- use
ClassName::func()to call - no
thispointer - can only access other
staticclass members
- use
class Player { public: static inline int playerCount = 0; // C++17 allows inline initialization Player() { playerCount++; } static int getCount() { return playerCount; // Valid: accessing a static variable // return health; // ERROR: cannot access non-static member without 'this' } private: int health = 100; }; int main() { Player p1; Player p2; // Called without needing an object instance: int total = Player::getCount(); // Returns 2 } 3. static on global variable -- Internal Linkage
use static for global make it private, so other files can not access it (even use extern)
// File01.cpp // static int sharedCounter = 10; // then compiler still work, but LINKER ERROR: undefined reference to int sharedCounter = 10; // External linkage by default // File02.cpp #include <iostream> extern int sharedCounter; // Compiler always trusts us, leaves it to the Linker... it tells compiler: "Look in other .cpp files for this" void printCounter() { std::cout << sharedCounter << "\n";// if use static, link will gives error here. } if we add static in above case, then in File02.cpp, Compiler will always works, but Linker will failed.
- prevent name collision
- file-level encapsulation
4. Extra Related Points
4.1 magic statics
- local
staticvars are thread safe
Logger& getLogger() { // Thread-safe initialization ("Magic Static"): // Only one thread constructs 'instance'. Others block until it's ready. static Logger instance; return instance; } 4.2 The Static Initialization Order Fiasco (SIOF)
- Global and class static variables are initialized before main() starts. Within a single
.cppfile, initialization from top to bottom. - global (or namespace-scope) static variables across different
.cppfiles, the initialization order is completely random (unspecified).
# file A depend on file B # run fileA.cpp --> fileB.cpp # undefined behavior even before main() run Solution:
wrap the variable inside function, make it a local static var, then it run inside main, and init only once.
// fileA.cpp std::string globalConfigPath = "/etc/app/config.json";// Global var #1 // fileB.cpp extern std::string globalConfigPath; // Declared in Config.cpp class Logger { public: Logger() { // !!! If Logger initializes BEFORE globalConfigPath, globalConfigPath is uninitialized memory! std::cout << "Loading logger from: " << globalConfigPath << std::endl; } }; // Global var #2 Logger globalLogger; fix:
Instead of defining globals directly at file scope, Meyers Singleton wraps each object inside a function as a static local variable.
// fileA.cpp std::string& getConfigPath() { static std::string path = "/etc/app/config.json"; // Initializes on first call return path; } // fileB.cpp Logger& getLogger() { static Logger instance; // Initializes on first call return instance; } Logger::Logger() { // Calling getConfigPath() guarantees 'path' is constructed right not before Logger finishes constructing std::cout << "Loading logger from: " << getConfigPath() << std::endl; } 4.2.1 don't use static in Header file .h
As it copy content to every file used it, will cause error, use inline instead in .h file (C++17)
4.2.2 Destruction Order
similarly, also need to prevent the Static Destruction Order Fiasco.(e.g., using std::shared_ptr)
Summary
- static local
- magic static -- thread safe for init
- static global -- Internal Linkage
- make global private --
extern - init unpredictable -- Meyer's Singleton
- make global private --
- static in class
- member: init
- function:
Class::func(),this, static member