ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

c – 共享对象中的模板单例基类

2019-10-03 07:05:26  阅读:159  来源: 互联网

标签:c linux shared-libraries


我目前正在将我的项目从Windows移植到Linux.

该项目包括一个“主”共享库,几个插件(也是共享库)和一个启动器应用程序.

在’main’共享库中,有一个模板单例类,另一个类可以继承来使用单例模式.

模板单例类实现如下:

    template<class T>
    class Singleton
    {
    public:
        static T* getInstance()
        {
          if(!m_Instance)
          {
            m_Instance = new T();
          }

          return m_Instance; 
        }
    private:
        static T* m_Instance;

    protected:
        Singleton()
        {
          assert(!m_Instance);
          m_Instance = (T*)this;
        }

        ~Singleton()
        {
          m_Instance = 0;
        }
    };

template<class T> T* Singleton<T>::m_Instance = 0;

从Singleton类继承的类是 – 例如 – Logger类.
所以,每当我打电话

Logger::getInstance()

我得到了一个有效的logger类实例.

对于Windows,这适用于多个DLL.

如果我在’main’dll中实例化记录器并尝试在插件A和B中获取实例,它将始终返回相同的实例.

但是在Linux上,我无法重现这种行为.对于插件A和B两者断言

assert(!m_Instance);

触发器和程序停止.

我需要做些什么来获得与Windows中使用dll相同的行为?

我尝试使用-rdynamic进行链接,但不幸的是,这并没有解决问题.

解决方法:

恕我直言,你能得到的最接近你的要求就是使用following pattern

#include <iostream>

template<class Derived>
class Singleton {
public:
    static Derived& instance() {
        static Derived theInstance;
        return theInstance;
    }

protected:
    Singleton() {}

private:
    Singleton(const Singleton<Derived>&);
    Singleton<Derived>& operator=(const Singleton<Derived>&);
};
class ASingleton : public Singleton<ASingleton> {
public:
    void foo() { std::cout << "foo() called ..." << std::endl; }
};
int main() {
    ASingleton& a = ASingleton::instance();
    a.foo();
    return 0;
}

无论您希望通过接口访问什么,都可以使用多重继承进行注入.虽然使用Singleton< Derived>的好处是基类有点值得怀疑,它只是提供了狭窄的instance()实现.

标签:c,linux,shared-libraries
来源: https://codeday.me/bug/20191003/1847639.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有