Search code examples
c++singletonsingleton-type

Do I need to destroy singleton instance in my case?


If the process is terminated after I use singleton instance like below. Is there memory leak is exist?

  1. If yes, How can I fix the problem?
  2. Do I need to add "destroyInstance" member function?
  3. If yes, when multi thread is already refer to the singleton instance, how can I assure multi thread safety? (Do I need to add reference count?)

I wonder that If I need to consider all of them, singleton pattern seems to very complex.

#include <mutex>

class Singleton 
{
    static Singleton *singletonInstance;
    Singleton() {}
    static std::mutex m_;

  public:

    static Singleton* getSingletonInstance()
    {
        std::lock_guard<std::mutex> lock(m_);
        if(singletonInstance == nullptr)
        {
            singletonInstance = new Singleton();
        }
        return singletonInstance;
    }
}

Solution

  • You don't need manual memory management for a singleton. Here's your example with std::unique_ptr:

    #include <memory>
    #include <mutex>
    
    class Singleton 
    {
        static std::unique_ptr<Singleton> singletonInstance;
        Singleton() {}
        static std::mutex m_;
    
      public:
    
        static Singleton* getSingletonInstance()
        {
            std::lock_guard<std::mutex> lock(m_);
            if (!singletonInstance)
            {
                singletonInstance = std::make_unique<Singleton>();
            }
            return singletonInstance.get();
        }
    };
    

    The std::unique_ptr destructor will be called when the process ends normally. Also, there is no need to synchonize destructor.

    But even better, you should use Scott Meyer's singleton:

    class Singleton {
    public:
        static Singleton& getSingletonInstance() {
            static Singleton instance;
            return &instance;
        }
    };
    

    The example above is thread safe, even though no explicit lock is used.


    For you Q3, even though the member function getSingletonInstance might be thread safe, usage of the singleton might not. Shared mutable state is inherently thread unsafe.