Static variables initialisation order

后端 未结 7 1200
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 15:20

C++ guarantees that variables in a compilation unit (.cpp file) are initialised in order of declaration. For number of compilation units this rule works for each one separat

7条回答
  •  难免孤独
    2020-11-22 15:58

    In addition to Martin's comments, coming from a C background, I always think of static variables as part of the program executable, incorporated and allocated space in the data segment. Thus static variables can be thought of as being initialised as the program loads, prior to any code being executed. The exact order in which this happens can be ascertained by looking at the data segment of map file output by the linker, but for most intents and purposes the initialisation is simultaeneous.

    Edit: Depending on construction order of static objects is liable to be non-portable and should probably be avoided.

提交回复
热议问题