模板单例基类在共享对象中 [英] Template singleton base class in shared object

查看:102
本文介绍了模板单例基类在共享对象中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm currently porting my project from Windows to Linux.

该项目包括一个主共享库,几个插件启动器应用程序。

The project consists of a 'main' shared library, several plugins (also shared libraries) and a launcher application.

在'main'共享库中有一个模板单例类,另一个类可以继承自使用singleton模式。

Within the 'main' shared library there's a template singleton class another class can inherit from to use the singleton pattern.

模板单例类实现如下:

    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类。
每当我调用

A class that inherits from the Singleton class is - for example - the Logger class. So whenever I call

Logger::getInstance()

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

I get a valid instance of the logger class.

如果我在'main'dll中实例化记录器并尝试在插件A和B中获取实例,它总是返回相同的实例。

If I instantiate the logger in the 'main' dll and try to get the instance in plugin A and B, it'll always return the same instance.

在Linux上,我不能重现这种行为。对于插件A和B的assert

On Linux however I can not reproduce this behavior. For both plugin A and B the assert

assert(!m_Instance);

触发器,程序停止。

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

What do I have to do to get the same behavior as I have in Windows with dlls?

我试图链接到-rdynamic但不幸的是这没有解决问题。

I tried linking with -rdynamic but unfortunately this didn't solve the problem.

推荐答案

IMHO最接近你可以得到的东西满足你的要求是使用以下模式

IMHO the closest thing you can get that suffices your requirements is something using the 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()实施。

Whatever you want to be accessible through an interface might be injected using multiple inheritance. Though the benefit of using a Singleton<Derived> base class is a bit questionable, it just provides that narrow instance() implementation.

这篇关于模板单例基类在共享对象中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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