代码之家  ›  专栏  ›  技术社区  ›  aCuria

自定义内存管理器

c++
  •  8
  • aCuria  · 技术社区  · 16 年前

    我正在尝试实现一个定制内存管理器,我想知道是否有更好的方法来实现这个函数,当我被问及关于空指针算法时,有几个人认为如果我在C++中有一个空洞,那么就有点错误了。

    // 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_;
    }
    
    3 回复  |  直到 14 年前
        1
  •  10
  •   Tergiver    16 年前

    在您的例子中,您需要一个“blob”内存块,它没有固有的类型,因此您正确地选择了void*来表示该blob。

    现在您需要将指针的大小增加到某个对象的大小。由于明显的原因,您不能对空指针执行算术运算,那么您该怎么做呢?投吧。这一点也不丢人。

        2
  •  6
  •   Merlyn Morgan-Graham    16 年前

    在C++中,在原始字节上,使用char *,不要想自己的任何东西。这是正确的做法(tm)。尤其是如果你把它包装在一个更高层次的结构中,就像你所做的那样。

        3
  •  2
  •   Puppy    16 年前