According to C++ Singleton design pattern I wrote a singleton template
template <typename T>
class Singleton
{
public:
static T& getInstance()
{
static T instance;
return instance;
}
protected:
Singleton() {}
~Singleton() {}
public:
Singleton(Singleton const &) = delete;
Singleton& operator=(Singleton const &) = delete;
};
And then I wrote a Logger singleton(The first one)
class Logger // not derived Singleton<Logger>
{
friend class Singleton<Logger>;
private:
Logger(){};
~Logger(){};
public:
void print(void){std::cout << "hello" << std::endl;}
};
int main(void)
{
Singleton<Logger>::getInstance().print(); // use Singleton<Logger>
return 0;
}
but I can also(The second one)
class Logger:public Singleton<Logger> // derived Singleton<Logger>
{
friend class Singleton<Logger>;
private:
Logger(){};
~Logger(){};
public:
void print(void){std::cout << "hello" << std::endl;}
};
int main(void)
{
Logger::getInstance().print(); // use Logger
return 0;
}
Then my questions are
- Is my singleton template correct?
- If singleton template is correct, the both Logger is correct?
- The difference between the first one and the second one,which one is better?
UPDATE
After the answers,I learned that the first one allows to have several logger and the singleton
class seems unneeded.SO I discard the first one.
About the seconde one I omit the destructor and then complier would generate a default inline public one. That seems more concise and more efficient.
class Logger:public Singleton<Logger> // derived Singleton<Logger>
{
friend class Singleton<Logger>;
private:
Logger(){};
public:
void print(void){std::cout << "hello" << std::endl;}
};
Logger(){}
andLogger(){}
is private – Modest