How is static variable initialization implemented by the compiler?

前端 未结 5 2036
旧巷少年郎
旧巷少年郎 2020-12-02 11:50

I\'m curious about the underlying implementation of static variables within a function.

If I declare a static variable of a fundamental type (char, int, double, etc.

5条回答
  •  温柔的废话
    2020-12-02 12:04

    You're right about everything, including the initialized flag as a common implementation. This is basically why initialization of static locals is not thread-safe, and why pthread_once exists.

    One slight caveat: the compiler must emit code which "behaves as if" the static local variable is constructed the first time it is used. Since integer initialization has no side effects (and calls no user code), it's up to the compiler when it initializes the int. User code cannot "legitimately" find out what it does.

    Obviously you can look at the assembly code, or provoke undefined behaviour and make deductions from what actually happens. But the C++ standard doesn't count that as valid grounds to claim that the behaviour is not "as if" it did what the spec says.

提交回复
热议问题