0

I have a static instance of a class defined in a function with {} initialiser in C++

Let us say in the function I increment a counter defined in that class.

In the constructor I have a print statement.

The print statement gets displayed first time the function gets called (not when main() starts) On subsequent calls of that function the constructor does not get called.

How does the function know that the initialisation code only happens on the first call and not subsequent? The only way I can think of is that there is some code that must check a flag to see if the constructor has been called and the flag is not part of the class but a hidden one.

Look forward to learning how it magically works.

MTailor
  • 39
  • 3
  • 3
    please post your code instead of describing it. Read [mcve] – 463035818_is_not_an_ai Nov 22 '21 at 10:33
  • Yes, there is code that checks whether local static objects have been initialized. What that code actually does is implementation-specific. – molbdnilo Nov 22 '21 at 10:34
  • 1
    https://stackoverflow.com/questions/898432/how-is-static-variable-initialization-implemented-by-the-compiler – Mat Nov 22 '21 at 10:35
  • 1
    Your observation is the expected behaviour. See [here](https://en.cppreference.com/w/cpp/language/storage_duration#Static_local_variables) for some more details. The meat of the matter is really that the standard specifies this behaviour, and also that it's thread safe. How it actually works under the hood is the concern of the compiler. – super Nov 22 '21 at 10:44
  • static objects once initialized do not get deleted until the end of the program – Vedant Matanhelia Nov 22 '21 at 11:30
  • Have a read of - [Static local variables](https://en.cppreference.com/w/cpp/language/storage_duration#Static_local_variables) _"...but are initialized the first time control passes through their declaration ..."_ – Richard Critten Nov 22 '21 at 11:46

0 Answers0