boost shared_ptr的自定义删除器

Kai*_*aan 3 c++ boost memory-management smart-pointers shared-ptr

我有一个关于为boost::shared_ptr构造函数提供自定义删除方法的问题.

例如,我有一个GameObjectFactory创建/销毁的类GameObjects.它有一个MemoryManager可以Allocate()/Deallocate()记忆的实例.CreateObject()返回一个GameObject,通过MemoryManager封装在一个中分配的boost::shared_ptr.

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
Run Code Online (Sandbox Code Playgroud)

我已经阅读了boost文档和我从stackoverflow获得的命中,但我无法正确使用它.我不明白为什么下面的dosnt工作.

这是我的代码;

#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
Run Code Online (Sandbox Code Playgroud)

zda*_*dan 8

shared_ptr期望删除器是一个接受指针类型(T*)的单个参数的函数.您正在尝试将其传递给成员函数,并且由于shared_ptr没有对IMemoryManager对象的引用,因此它将无法工作.要解决此问题,请创建一个接受指针对象并调用IMemoryManager :: Deallocate()的静态成员函数:

template <class T>
static void Deallocate(T* factoryObject)
{
    factoryObject->mMemoryMgr->Deallocate();
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以像这样创建shared_ptr:

boost::shared_ptr<T> ptr((T*) mMemoryMgr->Allocate(sizeof(T),UseMemoryPool), &IGameObjectFactory::Deallocate<T>);
Run Code Online (Sandbox Code Playgroud)