c++ - 用于 boost shared_ptr 的自定义删除器

标签 c++ memory-management boost shared-ptr smart-pointers

我有一个关于为 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

我已经阅读了 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

最佳答案

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>);

关于c++ - 用于 boost shared_ptr 的自定义删除器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9958129/

相关文章:

c++ - 现代 C++ 中的类型安全回调系统

c++ - 如何在我的 Boost::asio tcp 服务器刚开始运行时启动 "event"(AKA io_service.run())?

c++ - 为什么 lambda 对象中的局部变量是 const?

c++ - 执行策略之间的差异以及何时使用它们

c++ - 创建二次公式求解器 - 未在范围内声明的变量

java - Java 中的一个 boolean 值数组是否小于独立变量?

c++ - 如何配置为非阻塞unique_lock?

java - 用Java计算HashMap开销

C:从内存运行机器码

c++ - boost::counting_iterator range-v3 中的模拟