Search code examples
c++static-membersstatic-functions

Static variables release order


Please help,

The problem: core dumps in following code:

I have an abstract class SomeOtherClass, and have derived from it SomeOtherClassImpl.

Here is the code which causes the trouble:

class MyClass
{

public:

  void someFunction()
  {
    myVector().push_back(someOtherClassDefault());
  }

private:

  static std::vector<SomeOtherClass const *> & myVector()
  {
    static std::vector<SomeOtherClass const *> theVector;
    return theVector;
  }

  static SomeOtherClass const * someOtherClassDefault()
  {
    static SomeOtherClassImpl theDefault;
    return &theDefault;
  }

};

I have some static variables of MyClass type in other translation units.

The problem is weird as segmentation fault occures when program exits. Of course theDefault can be deallocated before theVector, but what's the difference? Both deallocated when main is already done.

You help will be much appreciated.


Solution

  • You are most probably hitting the static initialization fiasco, just on the opposite end. Basically, the order of destruction of objects of static duration is the reverse order of creation of the same. So if you have:

    void foo() {
       static type a;
    }
    void bar() {
       static type b;
    }
    int main() {
       foo();
       bar();
    }
    

    The construction will create first a, and then b, when main completes, it will destroy b then a. If you switch the order of the calls in main, then the order will be inverted. You have to be aware when dealing with variables of static duration on dependencies for this particular reason.