Dig into the difference between C++ visibility and lifetime

  • 2020-04-01 23:33:44
  • OfStack

The variable visibility (that is, scope) and Life span There are differences and connections.

A variable has no visibility at some point in the program, but its lifetime can still exist. For example, the visibility of a local static variable is in the function it is in, and it is not accessible outside the function, but its lifetime is the entire duration of the program. At the end of a variable's life, it has no visibility, just like a local variable, and as the stack space is freed, it no longer exists, so it cannot be accessed externally.

Determine the visibility of a variable is a variable be declared position (like a local static variable, as in function declarations, so only visible inside the function), and determine the lifetime of a variable is a variable in memory location (like the static local variables are not allocated on the stack, but the distribution of the static storage area in memory, so life is also unlike ordinary local variables).


Related articles: