If the process is terminated after I use singleton instance like below. Is there memory leak is exist?
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;
}
}
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.