Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When exactly is constructor of static local object called? [duplicate]

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-

like image 907
Honza Bambas Avatar asked Jun 17 '10 15:06

Honza Bambas


1 Answers

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.

like image 99
Stephen Avatar answered Sep 25 '22 16:09

Stephen