亲爱的大家,这会很难:我创建了一个游戏对象工厂来生成我想要的对象。但是,我遇到无法修复的内存泄漏。
内存泄漏是由代码示例底部的return new Object();产生的。
static BaseObject * CreateObjectFunc()
{
return new Object();
}
如何以及在哪里删除指针?我写了 bool ReleaseClassType()。尽管工厂运作良好,但 ReleaseClassType() 并未修复内存泄漏。
bool ReleaseClassTypes()
{
unsigned int nRecordCount = vFactories.size();
for (unsigned int nLoop = 0; nLoop < nRecordCount; nLoop++ )
{
// if the object exists in the container and is valid, then render it
if( vFactories[nLoop] != NULL)
delete vFactories[nLoop]();
}
return true;
}
在查看下面的代码之前,让我帮助您了解我的 CGameObjectFactory 创建指向函数的指针 创建特定对象类型。指针存储在 vFactories vector 容器中。
我之所以选择这种方式,是因为我解析了一个对象映射文件。我有对象类型 ID(整数值),我需要将它们转换为真实对象。因为我有超过 100 种不同的对象数据类型,所以我希望避免连续遍历很长的 Switch() 语句。
因此,为了创建对象,我通过 CGameObjectFactory::create() 调用 vFactories'['nEnumObjectTypeID']'() 来调用生成所需对象的存储函数。
vFactories 中相应函数的位置与 nObjectTypeID 相同,因此我可以使用索引来访问该函数。
所以问题仍然存在,如何进行垃圾回收并避免报告的内存泄漏?
#ifndef GAMEOBJECTFACTORY_H_UNIPIXELS
#define GAMEOBJECTFACTORY_H_UNIPIXELS
//#include "MemoryManager.h"
#include <vector>
template <typename BaseObject>
class CGameObjectFactory
{
public:
// cleanup and release registered object data types
bool ReleaseClassTypes()
{
unsigned int nRecordCount = vFactories.size();
for (unsigned int nLoop = 0; nLoop < nRecordCount; nLoop++ )
{
// if the object exists in the container and is valid, then render it
if( vFactories[nLoop] != NULL)
delete vFactories[nLoop]();
}
return true;
}
// register new object data type
template <typename Object>
bool RegisterClassType(unsigned int nObjectIDParam )
{
if(vFactories.size() < nObjectIDParam) vFactories.resize(nObjectIDParam);
vFactories[nObjectIDParam] = &CreateObjectFunc<Object>;
return true;
}
// create new object by calling the pointer to the appropriate type function
BaseObject* create(unsigned int nObjectIDParam) const
{
return vFactories[nObjectIDParam]();
}
// resize the vector array containing pointers to function calls
bool resize(unsigned int nSizeParam)
{
vFactories.resize(nSizeParam);
return true;
}
private:
//DECLARE_HEAP;
template <typename Object>
static BaseObject * CreateObjectFunc()
{
return new Object();
}
typedef BaseObject*(*factory)();
std::vector<factory> vFactories;
};
//DEFINE_HEAP_T(CGameObjectFactory, "Game Object Factory");
#endif // GAMEOBJECTFACTORY_H_UNIPIXELS
最佳答案
So the question remains, how to proceed with garbage collection and avoid reported memory leaks?
考虑使用 std::shared_ptr
或 boost::shared_ptr管理您的 BaseObject
指针所有权。
关于c++ - 游戏对象工厂 : Fixing Memory Leaks,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5189049/