Properly deleting a singleton

前端 未结 5 835
悲&欢浪女
悲&欢浪女 2021-01-24 23:07

I have the following code:

MyClass.h:

static MyMutex instanceMutex;
static MyClass* getInstance();
static void deleteInstance();

MyClas

5条回答
  •  一个人的身影
    2021-01-24 23:21

    In one project we inherited from some external company I've seen a whole nightmare class of errors caused by someone deleting the singleton. Perhaps in your rare case deleting the singleton doesn't have any side effects for the whole application, as you can be sure there is no instance of this singleton at use, but, generally, it's an excellent example of bad design. Someone could learn from your example and it would be a bad - even harmful - lesson. In case you need to clean up something in the singleton when the application exit, use the pattern ith returning reference to the singleton, like in example:

    #include 
    
    using namespace std;
    
    class singleton {
        private:
            singleton() {
                cout << "construktor\n";
            }
            ~singleton() {
                cout << "destructor\n";
            }
        public:
            static singleton &getInstance() {
                static singleton instance;
                cout << "instance\n";
                return instance;
            }
            void fun() {
                cout << "fun\n";
            }
    };
    
    
    int main() {
        cout << "one\n";
        singleton &s = singleton::getInstance();
        cout << "two\n";
        s.fun();
        return 0;
    }
    

提交回复
热议问题