什么时候应该删除动态创建的单例对象?

When the dynamically created singleton object should be deleted?

什么时候应该删除动态创建的单例对象?是否真的需要明确地(从析构函数中)删除对象,或者一旦程序退出,OS/System 将安全地声明未删除的内存?如果不删除会有什么后果?

一般情况下,建议在应用程序退出时销毁该对象。正如评论中提到的,大多数 OS 会在应用程序终止时释放内存,但是如果您需要在单例的析构函数中进行清理,那么您需要自己清理它(OS清理不会调用析构函数)。

我通常会在我的应用程序退出前删除它,但这并不总是最好的解决方案。我发现在某些情况下,创建单例只是为了删除,或者在删除后访问并重新创建。

您可以使用 atexit() 函数在创建单例时注册一个清理函数。例如:

static Singleton* s_instance = nullptr;

void cleanupSingleton() { 
     delete s_instance;
}


class Singleton {
public: 
    static Singleton* instance() { 
        if(s_instance == nullptr) {
            s_instance = new Singleton();
            std::atexit(cleanupSingleton);
        }
        return s_instance;
     }
 };

PS:不是最好的、线程安全的单例示例,但对于示例来说已经足够好了。

有关详细信息,请参阅有关 atexit() 函数的一些参考资料: cplusplus.com or cppreference.com

如果您使用单例,请使用 Meyers 的单例:

class Singleton {
public: 
    static Singleton& instance() { 
        static Singleton s_instance;

        return s_instance;
     }

    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;
private:
    Singleton() = default;
    ~Singleton() { /* Your clean up code */ }
 };

析构函数会在 main 结束后自动调用。