我有一个非常简单的内存管理器。 ConstructObject函数将一个ObjectInfo插入m_ObjectInfoMap中。但是我这样做的方式是调用ObjectInfo析构函数。如何更改功能以防止这种情况? 我想我可以使用一个指针(ObjectInfo * pObjectInfo = new ObjectInfo())并将其插入到地图中,但是我试图避免调用new运算符。
#define CONSTRUCT(T) static_cast<T*>(ObjectFactory::ConstructObject<T>( #T ))
#define DESTRUCT(object) ObjectFactory::DestructObject( object )
//dummy class so we can have a templated class as value to a map
class OObjectInfoInterface
{
};
template<class T>
class ObjectInfo : public OObjectInfoInterface
{
public:
ObjectInfo(){
m_Object = NULL;
m_Name = NULL;
m_Size = 0;
}
~ObjectInfo();
T* m_Object;
//used for things like memory profiling
const char* m_Name;
size_t m_Size;
};
template<class T>
ObjectInfo<T>::~ObjectInfo()
{
delete m_Object;
}
class ObjectFactory
{
public:
template <typename T>
static OObjectInterface* ConstructObject( const char* pName )
{
T* pNewObject = new T();
ObjectInfo<T> objectInfo;
objectInfo.m_Object = pNewObject;
objectInfo.m_Name = pName;
m_ObjectInfoMap[pNewObject] = objectInfo;//<--causes destructor of ObjectInfo to be called (which deletes pNewObject)
return pNewObject;
}
void ObjectFactory::DestructObject( void* pObject )
{
if ( pObject )
{
TObjectInfoMap::iterator it = m_ObjectInfoMap.find( pObject );
if ( it != m_ObjectInfoMap.end() )
{
m_ObjectInfoMap.erase(pObject);
}
else
{
LOG_ASSERT( 0, "object not found!");
}
}
}
};