If a variable is declared as static
in a function's scope it is only initialized once and retains its value between function calls. What exactly is its lifetime? When do its constructor and destructor get called?
void foo()
{
static string plonk = "When will I die?";
}
FWIW, Codegear C++Builder doesn't destruct in the expected order according to the standard.
... which is another reason not to rely on the destruction order!
Motti is right about the order, but there are some other things to consider:
Compilers typically use a hidden flag variable to indicate if the local statics have already been initialized, and this flag is checked on every entry to the function. Obviously this is a small performance hit, but what's more of a concern is that this flag is not guaranteed to be thread-safe.
If you have a local static as above, and 'foo' is called from multiple threads, you may have race conditions causing 'plonk' to be initialized incorrectly or even multiple times. Also, in this case 'plonk' may get destructed by a different thread than the one which constructed it.
Despite what the standard says, I'd be very wary of the actual order of local static destruction, because it's possible that you may unwittingly rely on a static being still valid after it's been destructed, and this is really difficult to track down.
The lifetime of function
static
variables begins the first time[0] the program flow encounters the declaration and it ends at program termination. This means that the run-time must perform some book keeping in order to destruct it only if it was actually constructed.Additionally, since the standard says that the destructors of static objects must run in the reverse order of the completion of their construction[1], and the order of construction may depend on the specific program run, the order of construction must be taken into account.
Example
Output:
[0]
Since C++98[2] has no reference to multiple threads how this will be behave in a multi-threaded environment is unspecified, and can be problematic as Roddy mentions.[1]
C++98 section3.6.3.1
[basic.start.term][2]
In C++11 statics are initialized in a thread safe way, this is also known as Magic Statics.The existing explanations aren't really complete without the actual rule from the Standard, found in 6.7: