设计模式:C++实现单例模式_风静如云的博客-CSDN博客_单例模式c++实现
介绍了实现单例模式的方式,如果工程中有很多类要实现为单例模式,那么每个类都需要如此实现一下,虽然并不复杂,但是确实有些麻烦,那么有没有可以更简洁的实现单例模式的方法呢,答案是通过模板:
#include <iostream>
using namespace std;
template<typename T>
class Singleton{
public:
static T& getInstance()
{
static T instance;
return instance;
}
protected:
Singleton() //声明为保护,允许派生类进行访问
{
cout<<"constructor called!"<<endl;
}
virtual ~Singleton()
{
cout<<"destructor called!"<<endl;
}
private:
Singleton(const Singleton&) = delete;
Singleton(Singleton&&