Nar*_*rek 3 c++ singleton templates static-members
头文件中的这个实现有什么问题?
template <typename T>
class Singleton
{
public:
static T* getInstance()
{
if (m_instance == NULL)
{
m_instance = new T();
}
return m_instance;
}
private:
static T* m_instance;
};
Run Code Online (Sandbox Code Playgroud)
我这样使用它:
typedef Singleton<MyClass> MyClassSingleton;
Run Code Online (Sandbox Code Playgroud)
我收到链接器错误:
error LNK2001: unresolved external symbol "private: static class MyClass * Singleton<class MyClass>::m_instance" (?m_instance@?$Singleton@VMyClass@@@@0PAVMyClass@@A)
Run Code Online (Sandbox Code Playgroud)
当我添加
template <typename T> T* Singleton<T>::m_instance = NULL;
Run Code Online (Sandbox Code Playgroud)
它有效,但我担心两件事:
Pra*_*ian 10
您可以通过m_instance在类定义之后添加成员的定义来修复错误.
template<typename T>
T* Singleton<T>::m_instance = nullptr;
Run Code Online (Sandbox Code Playgroud)
对于类模板,可以static在标题本身中添加成员的定义,并且不会导致ODR违规.
但是,正如其他人所建议的那样,最好将你的getInstance()定义改为
static T& getInstance()
{
static T instance;
return instance;
}
Run Code Online (Sandbox Code Playgroud)
C++ 11甚至保证函数局部static变量的创建instance是线程安全的.