Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 724
Valentin Avatar asked Feb 11 '26 04:02

Valentin


1 Answers

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

like image 105
Robinson Avatar answered Feb 16 '26 08:02

Robinson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!