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

前端 未结 8 1849
一向
一向 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:14

    One C++'ish way to do this is with Singletons.

    Essentially, write a function to return a reference to the object. To force it to initialize, make it a static object inside the function.

    Make a class static function that is vaguely like this:

    class MyClass {
       static MyClass& getObject()
       {
            static MyObject obj;
            return obj;
        }
    };
    
    0 讨论(0)
  • 2021-01-03 17:14

    Since you are using C++, you could always declare a global object (ie a global variable that references a class in statinit.cpp. As always, the constructor will be called on initialization and since the object is global, this will be called before main() is run.

    There is one very important caveat though. There is no guarantee as to when the constructor will be called and there is no way to explicitly order when each of these constructors is called. This will also probably defeat any attempt to check for memory leaks since you can no longer guarantee that all the memory allocated while running main has been deallocated.

    0 讨论(0)
提交回复
热议问题