Protecting a class from instantiation before main ()

I want my C ++ class to never be created before main () is entered. Is there any way to achieve this?

-

Some explanations:

I am writing an embedded application. My class should be static (located in BSS), but when creating an instance, it requires some resources that are not available before some things were initialized at the beginning of main (). Therefore, I want to make it a singleton Meyers. Ideally, I would like to make some statement that ensures that MyClass :: instance () is never called before main ().

+3
source share
6 answers

, , - , MyClass::enableConstruction(), . c'tor , , . , , - .

, . - , , , .

+2

- . , main(). , ? , , .

: CTQ, , , , , , . , , . ::instance(), bool, , , .

. , - , , , , ++ ( ). - .

+7

bool, , main()

factory , main()

+2

. , - , .

, , .

0

, main(), ​​:

bool wasMain (bool inMain = false) {
  static bool passedMain = false;
  return passedMain |= inMain;
}

wasMain (true), true , false .

: , :

bool wasMain (bool inMain = false) {
  static bool passedMain = false;
  if (inMain)
    passedMain = true;
  return passedMain;
}
0

, , main. .

MyClass * g_thing = 0;
int main()
{
    g_thing = new MyClass();
}

, , . ?

-1

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


All Articles