c ++模板单例静态指针初始化在头文件中 [英] c++ template singleton static pointer initialization in header file
问题描述
这个实现在头文件中有什么问题?
What is wrong with this implementation in header file?
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;
};
我这样使用:
typedef Singleton<MyClass> MyClassSingleton;
我遇到链接器错误:
error LNK2001: unresolved external symbol "private: static class MyClass * Singleton<class MyClass>::m_instance" (?m_instance@?$Singleton@VMyClass@@@@0PAVMyClass@@A)
当我添加
template <typename T> T* Singleton<T>::m_instance = NULL;
它可以工作,但我担心两件事:
it works, but I worry on two things:
- 静态成员应该在.cpp文件中定义,以便在所有编译单元中只有一个实例,即使您将头文件包含到10个源文件中
- 指针正在按标准初始化为NULL,为什么我需要显式初始化?
推荐答案
您可以通过在类定义之后添加 m_instance
成员的定义来修复错误。
You can fix your error by adding a definition for the m_instance
member after the class definition.
template<typename T>
T* Singleton<T>::m_instance = nullptr;
对于类模板,可以添加 static
For class templates, it's OK to add the definition of static
members within the header itself, and won't lead to ODR violations.
但是,正如其他人建议的那样,最好改变你的<$ c $> c> getInstance()定义为
But, as others have suggested, it's best to change you getInstance()
definition to
static T& getInstance()
{
static T instance;
return instance;
}
C ++ 11甚至保证创建函数local static
变量实例
将是线程安全的。
C++11 even guarantees that the creation of the function local static
variable instance
will be thread-safe.
这篇关于c ++模板单例静态指针初始化在头文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!