What's the C++ idiom equivalent to the Java static block? -


i have class static members, , want run code initialize them (suppose code cannot converted simple expression). in java, do

class myclass {     static int mydatum;      static {         /* computation sets mydatum */     } } 

unless i'm mistaken, c++ not allow such static code blocks, right? should doing instead?

i solution both of following options:

  1. initialization happens when process loads (or when dll class loaded).
  2. initialization happens when class first instantiated.

for second option, thinking of:

class staticinitialized {     static bool staticsinitialized = false;      virtual void initializestatics();      staticinitialized() {         if (!staticsinitialized) {             initializestatics();             staticsinitialized = true;         }     } };  class myclass : private staticinitialized {     static int mydatum;      void initializestatics() {         /* computation sets mydatum */     } }; 

but that's not possible, since c++ (at moment?) not allow initialization of non-const static members. but, @ least reduces problem of static block of static initialization expression...

for #1, if need initialise when process starts/library loaded, you'll have use platform-specific (such dllmain on windows).

however, if it's enough run initialisation before code same .cpp file statics executed, following should work:

// header: class myclass {   static int mydatum;    static int initdatum(); }; 

 

// .cpp file: int myclass::mydatum = myclass::initdatum(); 

this way, initdatum() guaranteed called before code .cpp file executed.

if don't want pollute class definition, can use lambda (c++11):

// header: class myclass {   static int mydatum; }; 

 

// .cpp file: int myclass::mydatum = []() -> int { /*any code here*/ return /*something*/; }(); 

don't forget last pair of parentheses - calls lambda.


as #2, there's 1 problem: can't call virtual function in constructor. you're better off doing hand in class instead of using base class it:

class myclass {   static int mydatum;    myclass() {     static bool onlyonce = []() -> bool {       myclass::mydatum = /*whatever*/;       return true;     }   } }; 

assuming class has 1 constructor, work fine; thread-safe, c++11 guarantees such safety initializing static local variables.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -