I recently read about the C++17 static inline
member declaration and thought that this will make templates a little bit cleaner, since static members can now be initialized inside a templated class.
Because of this I wanted to create a neat little Singleton template (since it is the perfect example where static members are needed).
Now to my questions: Is there something I potentially missed, i.e. are there possibilities to create copies of a derived Singleton? Is it a good idea to use CRTP for a Singleton in general? What a about the move constructor
, do I need to handle it as well?
Here is the template:
template < typename T >
class Singleton {
public:
static T& GetInstance() {
static MemGuard g; // clean up on program end
if (!m_instance) {
m_instance = new T();
}
return *m_instance;
}
Singleton(const Singleton&) = delete;
Singleton& operator= (const Singleton) = delete;
protected:
Singleton() { };
virtual ~Singleton() { }
private:
inline static T * m_instance = nullptr;
class MemGuard {
public:
~MemGuard() {
delete m_instance;
m_instance = nullptr;
}
};
};
And here a possible derived type:
class Test final : public Singleton<Test> {
friend class Singleton<Test>;
public:
void TestIt() { };
private:
Test() {}
~Test() { /* Test intern clean up */ }
};