c – 自定义内存管理器

我正在尝试实现一个自定义内存管理器,我想知道是否有更好的方法来实现这个功能,因为当我被问及无效指针算术时,有几个人认为如果我在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_;
}

解决方法

如果您需要一块内存来存储字符串(8位ANSI),那么将指向该缓冲区的指针声明为char并对其进行操作是有意义的.

在您的情况下,您需要一块“blob”内存块,它没有固有类型,因此您正确选择void *来表示该blob.

现在,您需要按某个对象的大小增加该指针.由于显而易见的原因,您无法对void指针执行算术运算,那么您该怎么办?施展它.没有羞耻感.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...