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
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;}
};
- Is my singleton template correct?
Yes it is.
- If singleton template is correct, the both Logger is correct?
Your first snippet allows to have several logger thanks to copy constructor. So in this regard, it is incorrect.
- The difference between the first one and the second one, which one is better?
If you fix first snippet to disallow also copy constructor, then you miss only the basic getInstance
and your Singleton
class seems unneeded.
With second snippet, you may even omit the destructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With