how to delete singleton object

前端 未结 3 704
不知归路
不知归路 2021-01-19 10:49

Assuming this implementation of a singleton pattern ( of course we should avoid Singleton: it is just question), I have just been thinking about static object being created.

3条回答
  •  情书的邮戳
    2021-01-19 11:05

    I prefer to not use a pointer.

    class Single
    {
    private:
       Single();
    
    public:
       Single& Instance()
       {
          static Single the_instance;
          Return the_instance;
       }
    };
    

    This singleton will live from the time Instance() is called until the application is exiting and performing the destruction of static objects. In this case the destructor of the singleton object will be called.

    In practice, even when using a pointer as in the original example, the memory will be reclaimed by the OS upon application exit. However in this case the object's destructor will not be called.

提交回复
热议问题