static binds an object's lifetime to the translation unit it is defined in.
Function
A static variable defined in a function keeps its value between function calls and can only be used within the function. It is initialised once when the function runs for the first time, and destroyed when the program terminates:
int next_id() {
static int id = 0;
return ++id;
}
next_id(); // 1
next_id(); // 2
next_id(); // 3Initialising a static local variable is thread-safe. If several threads call the function at the same time, only one initialises the variable and the others wait.
Class
A static member variable defined in a class is shared between all instances of the class. It can be accessed via a class or instance:
class Shape {
public:
static int count;
};
int Shape::count = 0;
int main() {
Shape s;
Shape::count++; // 1
s.count++; // 2
}Namespace
A static function or variable defined in a file (outside function or class) can only be used within that file. The definition is not shared across files. Two files can then have their own definition without a multiple definition error:
// a.cpp
static int helper() {
return 1;
}
// b.cpp
static int helper() {
return 2;
}Note
An unnamed namespace does the same thing and also works for classes:
namespace { int helper() { return 1; } }
Note
Avoid static variables in headers, as each file including the header gets its own separate copy.
Dan