c++allocationallocator

Custom deallocator with an std::vector doesn't get called


I am expecting this code to print "Hello world" - "Hello " when the memory is deallocated and "world" in main. However "Hello" never gets printed, meaning that my deallocator doesn't get called. What's the proper way to implement it?

#include <iostream>
#include <vector>

class MyAllocator : public std::allocator<uint8_t>
{
public:
  void deallocate(uint8_t* data, std::size_t size)
  {
    std::cout << "Hello ";
    std::allocator<uint8_t>::deallocate(data, size);
  }
};


int main()
{
  {
    std::vector<uint8_t, MyAllocator> v(100);
  }
  std::cout << "world\n";

  return 0;
}

I assume it just calls the default std::allocator<uint8_t>::deallocate() function, but I am not seeing a way to prevent it and make it call my function.


Solution

  • In fact your allocator will work if you define rebind:

    #include <iostream>
    #include <vector>
    
    class MyAllocator : public std::allocator<uint8_t>
    {
    public:
    
        template <typename U>
        struct rebind
        {
            typedef MyAllocator other;
        };
    
        void deallocate(uint8_t* data, std::size_t size)
        {
            std::cout << "Hello ";
            std::allocator<uint8_t>::deallocate(data, size);
        }
    };
    
    
    int main()
    {
      {
        std::vector<uint8_t, MyAllocator> v(100);
      }
      std::cout << "world\n";
    
      return 0;
    }
    

    Produces:

    Hello world