静态生存期

  • 这种生存期与程序的运行期相同。
  • 在文件作用域中声明的对象具有这种生存期。
  • 在函数内部声明静态生存期对象,要冠以关键字static 。

具有静态生存期的对象包含两种,第一种是在命名空间作用域中声明的对象,第二种是在局部作用域中使用关键字static声明的对象。静态生存期的含义是对象的生存期和程序的运行期相同。
需要特殊记忆的是第二种情况,当函数(局部作用域)中的变量采用static修饰时,该变量不会在每次调用后被销毁,也就是下一次调用该函数时依旧保存上一次调用的状态,同时该变量也不会在每次调用都被初始化。比如下面定义的变量speed:

  1. void duckRun(int inc) {
  2. static int speed = 666;
  3. speed = speed + inc;
  4. printf("Duck Running with speed %d \n", speed);
  5. }

其中被static修饰的speed初值为666,并不是每次调用该函数都会重新将speed赋值为666,而仅仅在speed被调用之前进行一次赋值,后面每次speed的值被修改都会被保存;每次调用duckRun()函数都会使用第一次的speed的值,即静态,可以理解为写在硬盘里了,每次读取都很快。
参考:
https://www.yuque.com/go/doc/72487755

动态生存期

  • 块作用域中声明的,没有用static修饰的对象是动态生存期的对象(习惯称局部生存期对象)。
  • 开始于程序执行到声明点时,结束于命名该标识符的作用域结束处。

    示范代码

    ```cpp

    include

using namespace std;

int i = 1; // i 为全局变量,具有静态生存期。

void other() {

static int a = 2;

static int b;

// a,b为静态局部变量,具有全局寿命,局部可见。

//只第一次进入函数时被初始化。

int c = 10; // C为局部变量,具有动态生存期,

//每次进入函数时都初始化。

a += 2; i += 32; c += 5;

cout<<”—-OTHER—-\n”;

cout<<” i: “<<i<<” a: “<<a<<” b: “<<b<<” c: “<<c<<endl;

b = a;

}

int main() {

static int a;//静态局部变量,有全局寿命,局部可见。

int b = -10; // b, c为局部变量,具有动态生存期。

int c = 0;

cout << “—-MAIN—-\n”;

cout<<” i: “<<i<<” a: “<<a<<” b: “<<b<<” c: “<<c<<endl;

c += 8; other();

cout<<”—-MAIN—-\n”;

cout<<” i: “<<i<<” a: “<<a<<” b: “<<b<<” c: “<<c<<endl;

i += 10; other();

return 0;

}

  1. <a name="MWjcV"></a>
  2. ## 作用:构造计数
  3. ```cpp
  4. #include <iostream>
  5. using namespace std;
  6. //静态数据成员用于构造函数的计数
  7. class box {
  8. private:
  9. int len;
  10. int wid;
  11. int hig;
  12. public:
  13. static int count;
  14. box(int x=2.0,int y=1,int z=3) {
  15. cout << "构造函数" << endl;
  16. len = x;
  17. wid = y;
  18. hig = z;
  19. count++;
  20. }
  21. int volume() {
  22. cout << "test" << endl;
  23. return len*wid*hig;
  24. }
  25. };
  26. int box::count = 0;//初始化box的静态成员
  27. int main()
  28. {
  29. box box1(1, 3, 5);
  30. box box2;
  31. //cout<<box1.volume()<<endl;
  32. //cout<<box2.volume()<<endl;
  33. cout<<"构造次数为"<<box2.count;
  34. return 0;
  35. }