Function-Level Static Variable Initialization
In C++, function-level static variables are a useful mechanism for maintaining state within functions. However, their allocation and initialization process sometimes raises questions.
Unlike globally declared variables, which are allocated and initialized at program start, function-level static variables are not allocated or initialized until the function is called for the first time.
Consider the following code snippet:
void doSomething() { static bool globalish = true; // ... }
In this example, the static variable globalish will not be allocated or initialized until the function doSomething() is invoked. To demonstrate this, let's analyze a test program:
#include <iostream> class test { public: test(const char *name) : _name(name) { std::cout << _name << " created" << std::endl; } ~test() { std::cout << _name << " destroyed" << std::endl; } std::string _name; }; test t("global variable"); void f() { static test t("static variable"); test t2("Local variable"); std::cout << "Function executed" << std::endl; } int main() { test t("local to main"); std::cout << "Program start" << std::endl; f(); std::cout << "Program end" << std::endl; return 0; }
Upon compilation and execution, the output reveals that the constructor for the static variable t in function f() is not called until the function is invoked for the first time:
global variable created local to main created Program start static variable created Local variable created Function executed Local variable destroyed Program end local to main destroyed static variable destroyed global variable destroyed
Therefore, function-level static variables are not allocated or initialized at program start, but rather at the first invocation of the function in which they are defined.
以上是C 中函數級靜態變數何時初始化?的詳細內容。更多資訊請關注PHP中文網其他相關文章!