Possible Duplicate:
What is the lifetime of a static variable in a C++ function?
Say we have a code like this:
Some class {
Some() { // the ctor code }
};
Some& globalFunction()
{
static Some gSome;
return gSome;
}
When exactly 'the ctor code' is executed? As for normal static variables before main() or at the moment we first call to 'globalFunction()'?
How is it on different platforms and different compilers (cl, gcc, ...) ?
Thanks
-hb-
The Some
constructor will be run on the first call to globalFunction()
. This is discussed in Scott Meyer's Effective C++, Item 4.
This is enforced by the standard.
Note, that there may still be a problem with the destructor! In general, it's not possible to know when it is safe to delete this object, another thread (maybe living past main) might call this function after the local static has been destroyed, for this reason, these objects are often 'leaked' by creating them with 'new'.
But, also note that creating static objects like this is not thread safe anyways.
Global static objects will be constructed before main, it an undefined order.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With