没有调用带有std :: vector的自定义deallocator

问题描述 投票:1回答:2

我期待这段代码打印“Hello world” - 当你的内存被释放时“Hello”和main中的“world”。但是“Hello”永远不会打印出来,这意味着我的解除分配器不会被调用。实施它的正确方法是什么?

#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;
}

我假设它只是调用默认的std::allocator<uint8_t>::deallocate()函数,但我没有看到一种方法来阻止它并让它调用我的函数。

c++ allocation allocator
2个回答
2
投票

实际上,如果定义重新绑定,则分配器将起作用:

#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;
}

生产:

你好,世界


0
投票

std::allocator定义成员template rebind<U>

并且std::vector正确地使用它来确保它以适当的大小和对齐方式分配正确的内存块,因此即使您通过了自定义分配器,重新绑定也会导致实际使用标准分配器。

有关分配器的潜在成员,请参阅http://en.cppreference.com/w/cpp/concept/Allocator

© www.soinside.com 2019 - 2024. All rights reserved.