Request for the detailed description of “Static Initialization Order Fiasco”

僤鯓⒐⒋嵵緔 提交于 2019-12-02 14:34:23

问题


I read about the SIOF in the faq-lite and still I really don't understand why the issue happens. I have a static library(.a) and I use that library to use its static const data member object type. Then that static const data member object type I use and assign to a global variable(object). But it seems that global variable is empty when I use that global variable to my main or to any local function. I know obviously that my issue is SIOF but I really don't understand why my static const data member object was not initialized.

It was static library so I guess when we created our static library the static const data member object was compiled and linked to that static library, correct me if I'm wrong..

//libsource.h
class foo
{
   public:
   ....

   public:
   static const barbar foofaa;
};

//libsource.cpp
const barbar foo::foofaa = barbar();

//main.cpp
#include <libsource.h>

barbar foos= foo::foofaa;

int main()
{
   //can't use foos because its empty
}

Please advice. Why that static const data member object was not initialized even if its in the static library?

Many thanks.


回答1:


The static initialization order fiasco is fairly straightforward: static objects in a single translation unit are initialized in the order in which they are declared, but there is no guarantee as to the order in which static objects in different translation units are initialized with respect to each other.

So, in your specific example, foos in main.cpp may be initialized before foo::foofaa, which is declared in libsource.cpp.



来源:https://stackoverflow.com/questions/4731011/request-for-the-detailed-description-of-static-initialization-order-fiasco

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