C++中的静态对象何时被销毁?


静态对象用关键字 static 声明。它们只初始化一次,存储在静态存储区域。静态对象只在程序终止时才会被销毁,即它们一直存在,直到程序终止。

下面给出了一个演示 C++ 中静态对象的程序。

示例

 在线演示

#include <iostream>
using namespace std;
class Base {
   public :
   int func() {
      int a = 20;
      cout << "The value of a : " << a;
   }
};
int main() {
   static Base b;
   b.func();
   return 0;
}

输出

上述程序的输出如下。

The value of a : 20

现在让我们了解一下上面的程序。

Base 类中的函数 func() 声明了一个 int 变量 a,然后显示 a 的值。展示此功能的代码片段如下。

class Base {
   public :
   int func() {
      int a = 20;
      cout << "The value of a : " << a;
   }
};

在主函数中,创建了类 Base 的静态对象 b。然后调用函数 func()。由于对象 b 是静态的,因此仅在程序终止时才会销毁该对象。展示此功能的代码片段如下。

int main() {
   static Base b;
   b.func();
   return 0;
}

更新于: 2020 年 6 月 26 日

2K+ 浏览

开启您的 事业

完成课程就能获得认证

开始
广告
© . All rights reserved.