自定义删除器用于boost shared_ptr

3
我有一个关于为boost::shared_ptr构造函数提供自定义删除方法的问题。
例如,我有一个GameObjectFactory类,它创建/销毁GameObjects。它拥有一个MemoryManager实例,可以Allocate()/Deallocate()内存。通过MemoryManager分配的GameObject通过boost::shared_ptr封装并返回CreateObject()
boost::shared_ptr析构时,它应该调用我的MemoryManager->Deallocate()方法。但是我无法正确地实现它;我得到了这些错误:
error C2276: '&' : illegal operation on bound member function expression
error C2661: 'boost::shared_ptr<T>::shared_ptr' : no overloaded function takes 2 arguments

我已经阅读了Boost文档和来自stackoverflow的相关内容,但是我仍然无法理解。我不明白为什么以下代码不能正常工作。
下面是我的代码:
#ifndef _I_GAMEOBJECT_MANAGER_H
#define _I_GAMEOBJECT_MANAGER_H

#include "../../Thirdparty/boost_1_49_0/boost/smart_ptr/shared_ptr.hpp"

#include "EngineDefs.h"
#include "IMemoryManager.h"
#include "../Include/Core/GameObject/GameObject.h"

namespace Engine
{
    class IGameObjectFactory
    {
    public:
        virtual ~IGameObjectFactory() { }

        virtual int32_t Init() = 0;
        virtual bool Destroy() = 0;
        virtual bool Start() = 0;
        virtual bool Stop() = 0;
        virtual bool isRunning() = 0;
        virtual void Tick() = 0;

        template <class T>
        inline boost::shared_ptr<T> CreateObject()
        {
            boost::shared_ptr<T> ptr((T*) mMemoryMgr->Allocate(sizeof(T)),&mMemoryMgr->Deallocate);


            return ptr;
        }

        template <class T>
        inline boost::shared_ptr<T> CreateObject(bool UseMemoryPool)
        {
            boost::shared_ptr<T> ptr((T*) mMemoryMgr->Allocate(sizeof(T),UseMemoryPool), &mMemoryMgr->Deallocate);


            return ptr;
        }

    protected:
        IMemoryManager* mMemoryMgr;
    };

}

#endif
2个回答

8

shared_ptr 期望的删除器是一个接受指针类型(T*)单个参数的函数。您正在尝试传递一个成员函数,由于 shared_ptr 没有对 IMemoryManager 对象的引用,所以它不起作用。为了解决这个问题,请创建一个接受指针对象并调用 IMemoryManager::Deallocate() 的静态成员函数:

template <class T>
static void Deallocate(T* factoryObject)
{
    factoryObject->mMemoryMgr->Deallocate();
}

您可以这样创建您的shared_ptr:
boost::shared_ptr<T> ptr((T*) mMemoryMgr->Allocate(sizeof(T),UseMemoryPool), &IGameObjectFactory::Deallocate<T>);

我仍然收到以下错误:error C2661: 'boost::shared_ptr<T>::shared_ptr' : 没有重载函数接受2个参数。使用最新的boost构建。 - KaiserJohaan
@KaiserJohaan:嗯,你使用的Boost版本是什么? - Nicol Bolas

1

boost::shared_ptr,以及{{link2:std::shared_ptr}}都可以使用谓词作为自定义删除器。因此,您可以传递一个函数或一个函数对象。您传递的是一个成员函数指针,但这不足以调用它,因为您没有对象的指针。您需要详细研究成员函数指针。有许多方法可以实现您想要的功能,我会编写自己的简单函数对象,它记住了对象工厂指针,并在shared_ptr调用适当的方法来删除它。此外,除非您真正需要shared_ptr,否则请考虑使用intrusive_ptr。它更加高效。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接