Ensure the order of construction and destruction of static variables in C ++

I am trying to find a good way to ensure the construction and destruction of static variables. As far as I know about static variables, they are created and destroyed in the following ways:

Based on the above rules, I wrote the following C ++ code so that the static variable is balways destroyed to a static variable a, which in my experiment guarantees the construction order and the destruction order:

in file Ah

class A {
 public:
  SomeClass* GetStatic() {
    static SomeClass a;
    return &a;
  }
}

in the Bh file:

#include "A.h"
class B {
 public:
  AnotherClass* GetStatic() {
    A::GetStatic();  // a dummy call to force the static local variable in 
                     // A::GetStatic() get initialized before the b.
    static AnotherClass b;
    return &b;
  }
}

In the above example, I put a dummy call A::GetStatic();right before the declaration static AnotherClass b;. If rule 3 is satisfied, this ensures that it is ainitialized to b. And because of rule 1, you can guarantee that it bwill be destroyed before a.

And my questions are:

  • Can I find out if I did what I did right, or can I make a mistake in a certain case with an angle?
  • Is there a better or better way to create or destroy static variables?

isocpp.org, , TODO: UP.

+4
2

, . , A, B.

, B- > A, . .

+3

, , , "".

google :

#pragma init_seg(XXX) - MSVS Intel ++ Windows

__attribute__ ((init_priority(XXX)) - GCC clang

, , static ( , MSVC, Intel ++, clang gcc), .

0

Source: https://habr.com/ru/post/1622033/


All Articles