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

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

Linda Hamilton
發布: 2024-11-15 09:39:03
原創
335 人瀏覽過

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

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板