【问题标题】:Why does my function-scoped static variable persist between object instances?为什么我的函数范围的静态变量在对象实例之间持续存在?
【发布时间】:2011-07-22 15:24:19
【问题描述】:

我今天发现了一个非常隐蔽的错误的来源。现在一切都已安全修复,但我想了解为什么当我执行以下代码时:

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

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

【问题讨论】:

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


    【解决方案1】:

    你的假设是错误的。函数范围的静态变量与全局变量非常相似。它只有一个全局实例。更多细节在这里:What is the lifetime of a static variable in a C++ function?

    【讨论】:

      【解决方案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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-24
        • 2014-11-21
        • 2011-07-18
        • 1970-01-01
        • 2013-10-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多