문제

Are static variables in C++ internal variables or external variables? Or can be both?


PS: It seems to me that (not sure it's correct):

  • Internal variables are assigned their values at compile time.

  • External variables are assigned their values at link time.

도움이 되었습니까?

해결책

Initialization depends on the type of the static variable.

  1. With fundamental types and initial values that can be computed at compile time, the variables initial value should be layed down in a section of the executable that is mapped into memory with copy on write semantics.

  2. However, the compiler can also decide to initialize static variables at runtime, typically before main() gets executed. But afaik, the only constraint is that initialization is finished when the variable is first used, and that static variables within a compilation unit are initialized in the order they are written (in case their initializers depend on one another).

The point is, that static variables are initialized before they are used by code called from main(), but it is not specified when this initialization happens. The compiler can do what it deems most efficient.

In any case, static variables live at least until main() exits or exit() is called. I am pretty sure that C++ will also call the destructors before terminating the process, but I don't know about that.

다른 팁

According to the C++ Standard

3 A name having namespace scope (3.3.6) has internal linkage if it is the name of — a variable, function or function template that is explicitly declared static; or,

As for your statement that

PS: I learned that • Internal variables are assigned their values at compile time.

• External variables are assigned their values at link time.

then it is wrong.

In my opinion you are trying to mix up two notions: static storage duration and program linkage.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top