我正在尝试实现一个自定义内存管理器,我想知道是否有更好的方法来实现这个函数,因为当我被问及无效指针算术时,有些人认为如果我在C++中有一个void*,那就非常错误.
// 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_;
}
Run Code Online (Sandbox Code Playgroud)
Ter*_*ver 10
如果您需要一块内存来存储字符串(8位ANSI),那么将指向该缓冲区的指针声明为char并对其进行操作是有意义的.
在您的情况下,您需要一块"blob"内存块,它没有固有类型,因此您正确选择void*来表示该blob.
现在,您需要将该指针增加一些对象的大小.由于显而易见的原因,您无法对void指针执行算术运算,所以您要做什么?投吧.没有羞耻.