2

I discovered the source of a really insidious bug today. It's all safely fixed now, but I'd like to understand why when I execute the following code:

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;
}

...I get the following:

Hello World
PrintDisabled
PrintEnabled
PrintEnabled
PrintEnabled

I had always assumed that the static would only persist between calls to the same instance of a class?

Jon Cage
  • 36,366
  • 38
  • 137
  • 215

2 Answers2

4

Your assumption is incorrect. A function-scoped static variable is very similar to a global variable. There is only one global instance of it. More details here: What is the lifetime of a static variable in a C++ function?

Community
  • 1
  • 1
Dark Falcon
  • 43,592
  • 5
  • 83
  • 98
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"

By it's very definition the static variable will persist between function calls and class instances. Unlike normal variables, a static variable's data is retained between calls and is only initialized once.

The difference between a global and static is that the global is available anywhere while the static is only available inside the scope that it was initialized. Both persist through the length of the program.

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

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

ssell
  • 6,429
  • 2
  • 34
  • 49