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

帅比萌擦擦* 提交于 2019-11-28 08:32:58

问题


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:


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.



来源:https://stackoverflow.com/questions/3063027/when-exactly-is-constructor-of-static-local-object-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!