我在 C++11 中实现了一个内存池。存储在内存池中的所有对象都需要从 MemoryPoolObject 类继承,但它们可能会使用多重继承。
当我分配一个新对象时,我使用 malloc 来创建它,然后使用放置构造函数 - 我可以这样做,因为我知道它的类型(allocate() 是一个模板函数,它将类型作为模板参数)。我还将其大小存储在其上的对象上(作为 MemoryPoolObject 类的成员变量)。
当我释放对象时,我想调用它的析构函数。但我不再知道对象类型。我确实知道它来自具有虚拟析构函数的 MemoryPoolObject。所以...如果我显式调用~MemoryPoolObject(),这会做正确的事情(包括调用任何多重继承基类的析构函数)?
这是一些代码。它没有显示未使用的对象如何在池中存储和检索。但这与手头的问题确实无关。
class BaseClass
{
public:
virtual ~BaseClass();
...
};
class MemoryPoolObject
{
public:
virtual ~MemoryPoolObject();
// In reality I don't just expose this, but for simplicity...
size_t m_ObjectSize;
};
class ChildClass : public BaseClass, public MemoryPoolObject
{
virtual ~ChildClass();
...
};
// allocation (simplified)
template<class T>
T* allocate()
{
size_t objectSize = sizeof(T);
T* obj = (T*)malloc(objectSize);
new(obj) T();
obj->m_ObjectSize = objectSize;
}
// deallocation (also simplified)
void deallocate(MemoryPoolObject* obj)
{
// Does this call ~BaseClass() and ~ChildClass()?
obj->~MemoryPoolObject();
}
所以...如果我显式调用
~MemoryPoolObject()
,这会做正确的事情(包括调用任何多重继承基类的析构函数)?
是的,它会的。
但是,我认为您可以稍微改变策略以使您的代码更直观。
重载operator new
and operator delete
inMemoryPoolObject
并让用户以通常的方式使用operator new
and operator delete
。
一个示例程序:
#include <iostream>
using namespace std;
void* allocate(size_t s)
{
// This is a simple implementation.
// To use a memory pool for allocating objects, this function
// and deallocate() need to be changed accordingly.
std::cout << "Allocating memory of size " << s << std::endl;
return new char[s];
}
void deallocate(void* ptr, size_t s)
{
std::cout << "Dellocating memory of size " << s << std::endl;
delete [] static_cast<char*>(ptr);
}
class MemoryPoolObject
{
public:
virtual ~MemoryPoolObject() {}
void* operator new (size_t s)
{
return allocate(s);
}
void operator delete (void* ptr, size_t s)
{
return deallocate(ptr, s);
}
};
class BaseClass
{
public:
virtual ~BaseClass() {}
};
class ChildClass : public BaseClass, public MemoryPoolObject
{
virtual ~ChildClass() {}
};
int main()
{
MemoryPoolObject* ptr = new ChildClass;
delete ptr;
}
输出
Allocating memory of size 16
Dellocating memory of size 16
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句