且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C++中的static变量

更新时间:2022-06-28 20:34:25

虽然是老生常谈,但下面这篇文章还是概括地很全面的。

C++中的static有以下三种不同的效果:
  1. 当用于成员变量时,表示它将由类分配管理而不是实例。
  2. 当在一个函数中时,数据将会被静态分配,在函数第一次被调用时初始化,且一直存在到程序退出。它当然也仅在当前函数中可用。这个特性经常被用于单例的延迟建构。 
  3. 当在一个编译单元中(如源文件),它可以在本单元中视为全局的,但对于其它单元却是不可见的。

第三种情况会在无命名空间中允许类定义中并未导出的声明 (Use (3) is somewhat discouraged in favor of unnamed namespaces that also allows for un-exported class declarations.)

第二种情况和类或实例无关,只是一个函数所拥有的变量,而且仅有一份。


但是确实有一种情况下,会使得函数中的静态变量不止一份。对于模板函数而言,函数自身在程序可能会存在多份,当然这和类与实例无关。下面是一个示例:
#include<stdio.h>

template<int num>
void bar()
{
    static int baz;
    printf("bar<%i>::baz = %i\n", num, baz++);
}

int main()
{
    bar<1>(); // Output will be 0
    bar<2>(); // Output will be 0
    bar<3>(); // Output will be 0
    bar<1>(); // Output will be 1
    bar<2>(); // Output will be 1
    bar<3>(); // Output will be 1
    bar<1>(); // Output will be 2
    bar<2>(); // Output will be 2
    bar<3>(); // Output will be 2
    return 0;
}

原文(Stack Overflow): Static variables in class methods