Using operator new and operator delete with a custom memory pool/allocator

后端 未结 3 1926
春和景丽
春和景丽 2020-12-07 03:13

I\'m working on a memory pool/memory allocator implementation and I am setting it up in a manor where only a special \"Client\" object type can draw from the pool.The client

3条回答
  •  春和景丽
    2020-12-07 03:31

    You might store additional information just before the returned memory address

    #include 
    #include 
    
    class Pool {
    public:
        static void* Alloc(std::size_t size) { return data; }
        static void Dealloc(void*) {}
    private:
        static char data[1024];
    };
    char Pool::data[1024];
    
    
    class Client
    {
    public:
        void* operator new(size_t size, Pool& pool);
        void operator delete(void* memory);
    };
    
    
    struct MemoryHeader {
        Pool* pool;
    };
    
    
    void* Client::operator new(size_t size, Pool& pool)
    {
        auto header = static_cast(pool.Alloc(sizeof(MemoryHeader) + size));
        std::cout << "    New Header: " << header << '\n';
        header->pool = &pool;
        return header + 1;
    }
    
    void Client::operator delete(void* memory)
    {
        auto header = static_cast(memory) - 1;
        std::cout << " Delete Header: " << header << '\n';
        header->pool->Dealloc(header);
    }
    
    int main()
    {
        Pool pool;
        Client* p = new(pool) Client;
        std::cout << "Client Pointer: " << p << '\n';
        delete p;
        return 0;
    }
    

提交回复
热议问题