mardi 23 janvier 2018

How to pass Custom allocator to std::basic_ostringstream? C++11

I want to use custom allocator to allocate memory from freelist for std::basic_ostringstream. Here is my custom allocator which I want to use it.

template <class Tp>

    struct NAlloc {
        typedef Tp value_type;
        typedef value_type* pointer;
        typedef const value_type* const_pointer;
        typedef value_type& reference;
        typedef const value_type& const_reference;
        typedef std::size_t size_type;
        typedef std::ptrdiff_t difference_type;

        NAlloc() = default;
        template <class T> NAlloc(const NAlloc<T>&) {}
        Tp* allocate(std::size_t n) {
            n *= sizeof(Tp);
            memoryPool *memPool = memoryPool::GetInstance(10);//get memory pool instance
            std::cout << "allocating " << n << " bytes\n";
            return static_cast<Tp*>(memPool->allocate(n)); //get memory from pool
        }
        void deallocate(Tp* p, std::size_t n) {
            std::cout << "deallocating " << n*sizeof*p << " bytes\n";
            memoryPool *memPool = memoryPool::GetInstance(10);
            memPool->deallocate(static_cast<void*>(p));//return memory to pool
        }

   template<typename U>
   struct rebind {
    typedef NAlloc<U> other;
   };

Then,

    typedef std::basic_string<char, std::char_traits<char>, NAlloc<char>> OstringStream;

Aucun commentaire:

Enregistrer un commentaire