How do I make an unreferenced object load in C++?

前端 未结 8 1905
一向
一向 2021-01-03 16:36

I have a .cpp file (let\'s call it statinit.cpp) compiled and linked into my executable using gcc. My main() function is

8条回答
  •  既然无缘
    2021-01-03 17:08

    Is the problem that the static items were never initialized, or is the problem that the static items weren't initialized when you needed to use them?

    All static initialization is supposed to be finished before your main() runs. However, you can run into issues if you initialize on static object with another static object. (Note: this doesn't apply if you are using primitives such as int)

    For example, if you have in file x.cpp:

    static myClass x(someVals);
    

    And in y.cpp:

    static myClass y = x * 2; 
    

    It's possible that the system will try to instantiate y before x is created. In that case, the "y" variable will likely be 0, as x is likely 0 before it is initialized.

    In general, the best solution for this is to instantiate the object when it is first used (if possible). However, I noticed above you weren't allowed to modify that file. Are the values from that file being used elsewhere, and maybe you can change how those values are accessed?

提交回复
热议问题