C++11实现泛型单例模式,支持任意参数类的对象创建。采用了C++11的可变参数模板和完美转发技术
#include <iostream>
#include <string>
#include <stdexcept>
using namespace std;
//单例类,包含任意参数的类实例。
template <typename T>
class Singleton
{
public:
template <typename... Args> //C++11可变参数模板
static T * Instance(Args&&... args)
{
if(m_pInstance==nullptr)
{
//使用完美转发,避免不必要的内存复制
m_pInstance=new T(std::forward<Args>(args)...);
}
return m_pInstance;
}
static T* GetInstance()
{
if(m_pInstance==nullptr)
{
throw logic_error("the instance is not init,please initialize the instance first");
}
return m_pInstance;
}
static void DestroyInstance()
{
delete m_pInstance;
m_pInstance=nullptr;
}
private:
Singleton(void);
Singleton(const Singleton&);
Singleton& operator=(const Singleton&);
virtual ~Singleton(void);
private:
static T* m_pInstance; //类实例
};
template <typename T>
T* Singleton<T>::m_pInstance=nullptr;
struct A
{
A(const string &)
{
cout<<"lvalue"<<endl;
}
A(const string &&x)
{
cout<<"rvalue"<<endl;
}
};
struct B
{
B(const string &)
{
cout<<"lvalue"<<endl;
}
B(const string &&x)
{
cout<<"rvalue"<<endl;
}
};
struct C
{
C(int x,double y)
{
cout<<"C: "<<x<<" "<<y<<endl;
}
void fun()
{
cout<<"test"<<endl;
}
};
int main()
{
cout<<"test begin"<<endl;
string str="bb";
Singleton<A>::Instance(str);
Singleton<B>::Instance(move(str));
Singleton<C>::Instance(1,3.14);
Singleton<C>::GetInstance()->fun();
Singleton<A>::DestroyInstance();
Singleton<C>::DestroyInstance();
return 0;
}