一个DLL中的单例? [英] Singleton in a DLL?

查看:294
本文介绍了一个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?

推荐答案

请参阅多个单例实例

您必须确保您的模板实例化在一个编译单元中完成,您将不得不将指针= 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();
}

这篇关于一个DLL中的单例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆