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.

6
  • 3
    please post your code instead of describing it. Read minimal reproducible example Commented Nov 22, 2021 at 10:33
  • Yes, there is code that checks whether local static objects have been initialized. What that code actually does is implementation-specific. Commented Nov 22, 2021 at 10:34
  • 1
    stackoverflow.com/questions/898432/… Commented Nov 22, 2021 at 10:35
  • 1
    Your observation is the expected behaviour. See here 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. Commented Nov 22, 2021 at 10:44
  • static objects once initialized do not get deleted until the end of the program Commented Nov 22, 2021 at 11:30

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.