为什么我的函数范围的静态变量在对象实例之间存在?

时间:2011-07-22 15:24:19

标签: .net variables static c++-cli persistence

我今天发现了一个非常阴险的虫子的来源。它现在已经安全地修复了,但是我想了解为什么当我执行以下代码时:

using namespace System;

ref class EvilClass
{
public:
    EvilClass()
    {

    }

    void Print()
    {
        static bool enablePrint = false;
        if( enablePrint )
        {
            Console::WriteLine("PrintEnabled");
        }
        else
        {
            Console::WriteLine("PrintDisabled");
        }
        enablePrint = true;
    }

};


int main(array<System::String ^> ^args)
{
    Console::WriteLine(L"Hello World");

    EvilClass^ ec = gcnew EvilClass();

    ec->Print();
    ec->Print();

    delete ec;
    ec = nullptr;

    ec = gcnew EvilClass();

    ec->Print();
    ec->Print();

    delete ec;
    ec = nullptr;

    return 0;
}

...我得到以下内容:

Hello World
PrintDisabled
PrintEnabled
PrintEnabled
PrintEnabled

我一直认为静态只会在调用同一个类实例之间持续存在?

2 个答案:

答案 0 :(得分:4)

您的假设不正确。函数范围的静态变量与全局变量非常相似。它只有一个全局实例。更多详情:What is the lifetime of a static variable in a C++ function?

答案 1 :(得分:2)

"a static member variable has the same value in any instance of the class and doesn't even require an instance of the class to exist"

根据它的定义,静态变量将在函数调用和类实例之间保持不变。与普通变量不同,静态变量的数据在调用之间保留,并且只初始化一次。

全局和静态之间的区别在于全局在任何地方都可用,而静态只在初始化范围内可用。两者都持续到整个计划的长度。

http://en.wikipedia.org/wiki/Static_variable

http://c.ittoolbox.com/documents/difference-between-static-global-variable-12174