Looking for a better C++ class factory

前端 未结 10 743
伪装坚强ぢ
伪装坚强ぢ 2020-12-29 00:40

I have an application that has several objects (about 50 so far, but growing). There is only one instance of each of these objects in the app and these instances get shared

10条回答
  •  南笙
    南笙 (楼主)
    2020-12-29 01:34

    Use a template class as the broker.
    Make the instance a static member of the function. It will be created on first use and automagically-destroyed when the program exits.

    template 
    class BrokeredObject
    {
        public:
            static Type& getInstance()
            {
                static Type theInstance;
    
                return theInstance;
            }
    }; 
    
    class TestObject
    {
        public:
           TestObject()
           {}
    };
    
    
    int main()
    {
        TestObject& obj =BrokeredObject::getInstance();
    }
    

提交回复
热议问题