user1235183 user1235183 - 1 month ago 24
C++ Question

Destruction Order of Meyer Singletons

To the following code:

class C {
public:
static C& Instance() {
static C c;
return c;
}

~C(){std::cout << "c destructed\n";}
private:
C(){}
};

class D{//similar to D but prints `d destructed` on destruction
//...

int main()
{
auto c = C::Instance();
auto d = D::Instance();
}
//outputs (with gcc)
//d destructed
//c destructed
//d destructed
//c destructed


i have a couple of question:


  1. Is the order of destruction calls well defined? (even if class C and D are defined in different source-files)

  2. If it is well defined is this behaviour portable?


Answer

If your code is all in the same compilation unit, the order is specified (essentially, the statics are constructed in order of their definition, and destructed in reverse order).

If the statics are defined in different compilation units, the order of construction is unspecified. The order of destruction is the reverse of the order of construction but the reverse of an unspecified ordering is also an unspecified ordering.

So, if the statics are all defined in one compilation unit, the order of construction (and therefore of destruction) is the same between compilers. If the statics are defined in different compilation units, the order of construction, and therefore the order of destruction, is not guaranteed to be consistent between compilers.