问题描述
我想实现一个自定义内存管理器,我想知道是否有一个更好的方法来实现这个函数,当我被问到void指针算术,几个人认为,如果我在C ++中有一个void *一些是非常错误的。
I am trying to implement a custom memory manager and I am wondering if there is a better way to implement this function, as when I am asked about void pointer arithmetic, several people thought that if I had a void* in C++, something was very wrong.
// allocates a page of memory.
void ObjectAllocator::allocatePage()
{
//if(OAStats_.PagesInUse_ >= Config_.MaxPages_)
//throw exception
void* buffer = ::operator new(OAStats_.PageSize_); // allocate memory, no constructor call.
// =============== Setup the PageList_ ===============
GenericObject* pNewNode = ::new(buffer) GenericObject(); // Construct GenericObject for the pagelist.
pNewNode->Next = PageList_->Next; // pNewNode points to wherever PageList_ pointed to.
PageList_->Next = pNewNode; // PageList_ points to pNewNode
pNewNode = NULL; // dont need this handle anymore
buffer = static_cast<char*>(buffer) + sizeof(GenericObject); // move pointer to point after the generic object.
// =============== Setup the FreeList_ ===============
for(int i=0;i<Config_.ObjectsPerPage_;++i)
{
static GenericObject* pPreviousNode = NULL; // static variable to hold the previous node
pNewNode = ::new(buffer) GenericObject(); // Construct GenericObject for the freelist.
pNewNode->Next = pPreviousNode;
pPreviousNode = pNewNode;
buffer = static_cast<char*>(buffer) + OAStats_.ObjectSize_; // move pointer by ObjectSize.
++OAStats_.FreeObjects_;
}
FreeList_->Next = pNewNode;
++OAStats_.PagesInUse_;
++OAStats_.Allocations_;
}
推荐答案
内存用于存储字符串(8位ANSI),所以将一个指向该缓冲区的指针声明为char并对其进行操作是有意义的。
If you need a block of memory for for storing a string (8-bit ANSI), it makes sense to declare a pointer to that buffer as char and operate on it.
需要一个blob的内存块,它没有固有的类型,所以你正确地选择void *来表示这个blob。
In your case, you need a block of memory that is a 'blob', it has no inherent type, so you correctly chose void* to represent that blob.
现在你需要增加指针由一些对象的大小。你不能对一个void指针执行算术的明显的原因,所以你做什么?投射它。没有什么可耻的。
Now you need to increment that pointer by the size of some object. You cannot perform arithmetic on a void pointer for obvious reasons, so what do you do? Cast it. There is no shame in that.
这篇关于自定义内存管理器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!