Singleton在DLL? [英] Singleton in a DLL?
问题描述
所以我试图将一个项目中的某些东西导出到DLL。无论如何,一些项目使用单例类非常重。
So i am trying to export somethings in a project to DLL. Anyways a few of the projects use a singleton class very heavily.
template <typename T>
class DLL_IMP VA_Singleton {
protected:
VA_Singleton () {};
~VA_Singleton () {};
public:
static T *Get(){
return (static_cast<T*> (a_singleton));
}
static void Delete(){
if(a_singleton == NULL) {
delete a_singleton;
}
}
static void Create(){
a_singleton = GetInstance();
if(a_singleton == NULL){
a_singleton = new T;
}
}
private:
static T *a_singleton;
};
template <typename T> T *VA_Singleton<T>::a_singleton = NULL;
我得到导出工作正常,但是当它到导入它说明:
I got the export working fine, but when it comes to importing it states this:
template <typename T> T *VA_Singleton<T>::a_singleton = NULL;
不能使用DLLImport。这是我第一次真正使用DLL在一个工作环境。
Does not work with DLLImport. This is the first time ive ever really worked with DLL's in a work enviroment. Does anyone have any ideas?
推荐答案
请参阅 http://stackoverflow.com/questions/738933/multiple-singleton-instances
您必须确保模板实例化在一个编译单元中完成,您必须将指针= NULL初始化移动到CPP文件。在其他DLL中,您必须使用 extern
模板。
You will have to ensure that your template instantiation is done in one compilation unit, and you will have to move the pointer = NULL initialization to the CPP file. In other DLLs, you'll have to use extern
templates.
如果你坚持使用模板单例来处理多个DLL,你也可以定义一个返回单例实例的短包装函数,这样模板实例化只在一个编译单元中完成。
If you are stuck with getting templated singletons to work over multiple DLLs, you could also define a short wrapper function that returns your singleton instance so that the template instantiation is done in one compilation unit only.
示例:
template class Singleton<T>;
__declspec(dllexport/dllimport) T& getInstanceForMyType();
// in the cpp file:
T& getInstanceForMyType()
{
return Singleton<MyType>::getInstance();
}
这篇关于Singleton在DLL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!