2017-04-01 86 views
0

只是運行這個自定義內存分配器頭文件的例子,我只是想更好地理解一些編寫的代碼。自定義內存分配器示例(需要一些說明)

class Allocator 
{ 
public: 
    Allocator(size_t size, void* start) 
    { 
     _start   = start; 
     _size   = size; 

     _used_memory  = 0; 
     _num_allocations = 0; 
    } 

    virtual ~Allocator() 
    { 
     ASSERT(_num_allocations == 0 && _used_memory == 0); 

     _start = nullptr; 
     _size = 0; 
    } 

    virtual void* allocate(size_t size, u8 alignment = 4) = 0; 

    virtual void deallocate(void* p) = 0; 

    void* getStart() const 
    { 
     return _start; 
    } 

    size_t getSize() const 
    { 
     return _size; 
    } 

    size_t getUsedMemory() const 
    { 
     return _used_memory; 
    } 

    size_t getNumAllocations() const 
    { 
     return _num_allocations; 
    } 

protected: 
    void*   _start; 
    size_t  _size; 

    size_t  _used_memory; 
    size_t  _num_allocations; 
}; 

namespace allocator 
{ 
    template <class T> T* allocateNew(Allocator& allocator) 
    { 
     return new (allocator.allocate(sizeof(T), __alignof(T))) T; 
    } 

    template <class T> T* allocateNew(Allocator& allocator, const T& t) 
    { 
     return new (allocator.allocate(sizeof(T), __alignof(T))) T(t); 
    } 

    template<class T> void deallocateDelete(Allocator& allocator, T& object) 
    { 
     object.~T(); 
     allocator.deallocate(&object); 
    } 

    template<class T> T* allocateArray(Allocator& allocator, size_t length) 
    { 
     ASSERT(length != 0); 

     u8 headerSize = sizeof(size_t)/sizeof(T); 

     if(sizeof(size_t)%sizeof(T) > 0) 
      headerSize += 1; 

     //Allocate extra space to store array length in the bytes before the array 
     T* p = ((T*) allocator.allocate(sizeof(T)*(length + headerSize), __alignof(T))) + headerSize; 

     *(((size_t*)p) - 1) = length; 

     for(size_t i = 0; i < length; i++) 
      new (&p[i]) T; 

     return p; 
    } 

    template<class T> void deallocateArray(Allocator& allocator, T* array) 
    { 
     ASSERT(array != nullptr); 

     size_t length = *(((size_t*)array) - 1); 

     for(size_t i = 0; i < length; i++) 
      array[i].~T(); 

     //Calculate how much extra memory was allocated to store the length before the array 
     u8 headerSize = sizeof(size_t)/sizeof(T); 

     if(sizeof(size_t)%sizeof(T) > 0) 
      headerSize += 1; 

     allocator.deallocate(array - headerSize); 
    } 
}; 
  1. 爲什麼啓動參數需要/這裏使用?如果我想分配一些空間,我不需要指定需要分配多少內存?

  2. 如果我想創建一個簡單的線性自定義內存分配器,是否還需要包含前兩個模板?

  3. 對於這個片段new (&p[i]) T;爲什麼模板類型名稱在最後?

謝謝!

回答

1

1)開始存儲指向由此分配器分配的「真正」分配的內存的指針,並且稍後需要將其傳遞給相應的自由函數。

2)我認爲這將是更好的從頭

3)這個表達式是一個放置新操作符調用和& P [i]爲其中T類型的對象將被構造的地址寫分配器