首頁 >後端開發 >C++ >C 中函數級靜態變數何時初始化?

C 中函數級靜態變數何時初始化?

Linda Hamilton
Linda Hamilton原創
2024-11-15 09:39:03340瀏覽

When are function-level static variables in C++ initialized?

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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn