views:

92

answers:

1

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-

+1  A: 

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.

Stephen
Thank you Stephen, can I cite you in a mozilla bug comment?
Honza Bambas
This question reminded me of an excellent article on singletons and thread safety in C++ : http://www.drdobbs.com/184405726 and http://www.drdobbs.com/184405772
fingerprint211b
@Honza : sure thing, please comment with a link, I'd like to read it :) [note: that there are (as always) some special cases to this - especially the thread safety part... so in some special conditions it may be ok]
Stephen
@fingerprint : thanks for those links, I'll be reading those later.
Stephen
@all : FWIW, the answers from the duplicate question are good reads too.
Stephen
@Stephen: This object already has a well defined point when it is deleted (automatically). Also it may not be technically thread safe but gcc makes it thread safe and I have seen discussions where MS compiler will also make it thread safe soon. Saying the order of global statics is undefined is not accurate enough. It is defined for certain situations (in the same compilation unit).
Martin York
@Martin : that's why I commented that "in special conditions it may be ok", but itemizing those wasn't something I wanted to get in to. And you're right, i should've been more accurate about order of construction.
Stephen
@Stephen : commented to Mozilla bug 569629.
Honza Bambas