在C++中,静态变量在程序启动时初始化,只初始化一次。静态变量的初始化有两种方式:局部静态变量和全局静态变量。
在函数内部定义的静态变量,它在第一次调用该函数时被初始化,之后每次调用函数时不再重新初始化,而是保持上一次调用结束时的值。局部静态变量的初始化使用关键字static
进行修饰。例如:
void foo() {
static int count = 0; // 局部静态变量
count++;
std::cout << "This function has been called " << count << " times." << std::endl;
}
int main() {
foo();
foo();
foo();
return 0;
}
输出结果:
This function has been called 1 times.
This function has been called 2 times.
This function has been called 3 times.
在函数外部定义的静态变量,它在程序启动时被初始化,只初始化一次。全局静态变量的初始化不需要使用关键字static
进行修饰。例如:
int global_count = 0; // 全局静态变量
void foo() {
global_count++;
std::cout << "This function has been called " << global_count << " times." << std::endl;
}
int main() {
foo();
foo();
foo();
return 0;
}
输出结果:
This function has been called 1 times.
This function has been called 2 times.
This function has been called 3 times.
注意:局部静态变量和全局静态变量的初始化顺序在不同的编译单元中是未定义的,但在同一编译单元中的初始化顺序是确定的。如果需要在不同编译单元之间进行同步初始化,可以使用互斥锁(mutex)等同步机制。