代码之家  ›  专栏  ›  技术社区  ›  Simon Linder

静态变量未初始化

  •  4
  • Simon Linder  · 技术社区  · 15 年前

    对于一个静态变量,我有一个奇怪的问题,它显然没有按照应该的方式初始化。
    我有一个庞大的项目可以在Windows和Linux上运行。由于Linux开发人员没有这个问题,我建议这是某种有线的Visual Studio东西。

    头文件

    class MyClass
    {
        // some other stuff here
        ...
        private:
            static AnotherClass* const Default_;
    };
    


    cpp文件

    AnotherClass* const MyClass::Default_(new AnotherClass(""));
    MyClass(AnotherClass* const var)
    {
        assert(Default_);
        ...
    }
    

    问题是 Default_ 总是 NULL . 我还尝试在初始化该变量时使用断点,但无法捕获它。

    另一个班也有类似的问题。
    cpp文件

    std::string const MyClass::MyString_ ("someText");
    MyClass::MyClass()
    {
        assert(MyString_ != "");
        ...
    }
    

    在这种情况下 MyString_ 总是空的。所以再次未初始化。
    有人知道吗?这是Visual Studio设置问题吗?
    干杯西蒙

    编辑:
    我还遇到了静态初始化失败。但我不确定这是否是问题所在,因为Linux编译器没有问题。在这种情况下,编译器的反应应该是相同的吗?

    4 回复  |  直到 15 年前
        1
  •  6
  •   Tomek    15 年前

    我建议您将静态成员函数与静态变量一起使用,而不是使用静态变量本身:

    class MyClass
    {
        // some other stuff here
        ...
        private:
            static AnotherClass* const getAnotherClass();
    };
    
    AnotherClass *const MyClass::getAnotherClass()
    {
        static AnotherClass *const p = new AnotherClass("");
        return(p);
    }
    

    标准保证当函数第一次被调用时P被初始化一次,所以你总是得到正确的初始化对象(除非你已经耗尽了内存或者你的构造函数抛出了)。

    请注意-这可能是线程安全的,也可能不是线程安全的(真正取决于编译器)。

    还有另一个注意事项——现在你必须忍受“内存泄漏”,因为它几乎不可能决定何时销毁对象,而且你没有办法将p重置为空。

        2
  •  3
  •   sth    15 年前

    如果在初始化其他静态变量时发生这种情况,您可能会看到 static initialization fiasco .

        3
  •  2
  •   Roddy    15 年前

    在这种情况下,编译器的反应应该是相同的吗?

    不,据我所知,各个编译单元的初始化顺序是不确定的。所以Linux开发人员很幸运。今天。明天,谁知道?

        4
  •  0
  •   sbi    15 年前

    在我的机器上工作(tm):

    #include <iostream>
    #include <cassert>
    
    class AnotherClass
    {
    public:
        AnotherClass(const char*) {}
    };
    
    class MyClass
    {
    public:
        MyClass(AnotherClass* const var);
    private:
        static AnotherClass* const Default_;
    };
    
    AnotherClass* const MyClass::Default_(new AnotherClass(""));
    
    MyClass::MyClass(AnotherClass* const var)
    {
        assert(Default_);
        std::cout << "Worked!\n";
    }
    
    int main()
    {
        MyClass tester(NULL);
        return 0;
    }
    

    我想问题是 MyClass::MyClass() 作为另一个静态变量的构造函数调用。静态变量的初始化并不总是按照您希望的顺序进行。