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