Singleton Destructors

后端 未结 12 1821
一整个雨季
一整个雨季 2021-01-31 03:55

Should Singleton objects that don\'t use instance/reference counters be considered memory leaks in C++?

Without a counter that calls for explicit deletion of the singlet

12条回答
  •  無奈伤痛
    2021-01-31 04:22

    In languages like C++ that don't have garbage collection it is best practice to clean up before termination. You can do this with a destructor friend class.

    class Singleton{
    ...
       friend class Singleton_Cleanup;
    };
    class Singleton_Cleanup{
    public:
        ~Singleton_Cleanup(){
             delete Singleton::ptr;
         }
    };
    

    Create the clean up class upon starting the program and then upon exiting the destructor will be called cleaning up the singleton. This may be more verbose than letting it go to the operating system but it follows RAII principles and depending on the resources allocated in your singleton object it might be necessary.

提交回复
热议问题