0

我正在为一个程序编写一个小型插件系统。它的某些部分已经完成,加载文件并调用构造函数工作。

在其中一个函数中,我需要将一些(类)指针传递回处理程序,这就是我得到段错误的地方。

在程序中:

class RenderInterface {
    public:
        RenderInterface();
        virtual ~RenderInterface();

        void RegisterBufferInterface(BufferInterface* interface)
        {
             bInterface = interface; // <---- this is where segfault occurs
        }
        void RegisterCameraInterface(CameraInterface* interface){}
        void RegisterRenderInterface(RenderInterface* interface){}

        static RenderInterface* GetSingletonPtr()
        {
            return _singleton;
        }

    private:
        static RenderInterface* _singleton;

        BufferInterface* bInterface;
        CameraInterface* cInterface
        RenderInterface* rInterface;
};

RenderInterface::_singleton 在其他地方设置为 0。

在注册函数中(在 dll 中):

class BInterface : public BufferInterface {
    public:
        ... various stuff ....
}

class GLPlugin : public Plugin {
    public:
        Plugin() : bInterface(0) {}
        ~Plugin(){}

        void Initialize() // <--- is called after dll has been loaded
        {
            bInterface = new BInterface();

            InterfaceManager::GetSingletonPtr()->RegisterBufferInterface(bInterface); // segfault
            // register other stuff
        }
    private:
        BufferInterface* bInterface;
};

我缺少什么让这个工作?还有另一种方法吗?

编辑:在简化代码时错过了 BufferInterface 之后的 *,感谢 Luchian

4

1 回答 1

3

好吧,它崩溃了,因为你从来没有初始化你的单例:

static RenderInterface* GetSingletonPtr()
{
    return _singleton;
}

我假设你在你的实现文件中初始化_singletonNULL在这种情况下你需要:

static RenderInterface* GetSingletonPtr()
{
    if ( !_singleton )
        _singleton = new RenderInterface;
    return _singleton;
}

其他一些提示:

  • 在使用单例之前评估其他选项
  • 实现析构函数通常意味着您还需要一个复制构造函数和一个赋值运算符(三规则)
  • 如果您的班级确实是单例,那么构造函数不应该是private吗?
  • bInterface = new BInterface();是非法的,因为bInterface它是一个对象,而不是一个指针。
于 2012-04-16T00:08:31.247 回答