Properly deleting a singleton

前端 未结 5 910
悲&欢浪女
悲&欢浪女 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:29

    I prefer to implement singletons in C++ in the following manner:

    class Singleton
    {
    public:
        static Singleton& instance()
        {
            static Singleton theInstance;
            return theInstance;
        }
    
        ~Singleton()
        {
            // Free resources that live outside the processes life cycle here,
            // if these won't automatically be released when the occupying process 
            // dies (is killed)!
            // Examples you don't have to care of usually are:
            // - freeing virtual memory
            // - freeing file descriptors (of any kind, plain fd, socket fd, whatever)
            // - destroying child processes or threads
        }
    
    private:
        Singleton()
        {
        }
    
        // Forbid copies and assignment
        Singleton(const Singleton&);
        Singleton& operator=(const Singleton&);
    };
    

    You can have locking mechanisms also, to prevent concurrent instantiation from multiple threads (will need a static mutex of course!). But deletion is left to the (OS specific) process context here.
    Usually you don't need to care about deletion of singleton classes, and how their acquired resources are released, because this is all handled by the OS when a process dies.
    Anyway there might be use cases, when you want to have your singleton classes some backup points on program crash situations. Most C++ crt implementations support calling destructors of statically allocated instances, but you should take care not to have ordered dependencies for any of those destructors.

提交回复
热议问题