C ++将分配器和初始化器与boost循环缓冲区一起使用

C++ Using allocator and initializer with boost circular buffer

我想弄清楚如何为 boost::circular_buffer 使用以下构造函数:

circular_buffer(capacity_type buffer_capacity, size_type n, const_reference item, const allocator_type& alloc = allocator_type());

我有一个习惯class:

template<class T> class Custom
{
  public:

    Custom() :
      time(0.0)
    {}

    double time;
    T data_;
};

我的循环缓冲区使用构造函数定义,只接受一个容量:

boost::circular_buffer<Custom<T>> buffer(10);

我对分配器的工作不多,我想在构造时用 default/empty/zero 值初始化我的缓冲区,上面提到的构造函数似乎是使用 boost::circular_buffer,但是我不确定如何使用 boost 构造函数。如果它是普通向量,我想我可以执行以下操作:

int num_elements = 10;
Custom<T> custom;
std::vector<Custom<T>> buffer(10, custom);

我真的找不到任何具体的示例,因此非常感谢您的帮助或指导。

就像你的 std::vector 调用一样,你没有为 Custom 指定分配器并使用默认值,你可以用 boost::circular_buffer 做同样的事情。唯一的区别是 boost::circular_buffer 有一个额外的参数允许您同时设置缓冲区中默认构造对象的容量和数量。这意味着如果你想要一个完整的 boost::circular_buffer 那么你会使用:

int num_elements = 10;
Custom<T> custom;
boost::circular_buffer<Custom<T>> buffer(num_elements, num_elements, custom);

它给你一个 boost::circular_buffer,容量为 num_elements,里面有 num_elements 个默认分配的对象。

您还可以:

boost::circular_buffer<Custom<T>> buffer(num_elements, num_elements/2, custom);

将容量设置为 num_elements,但仅使用默认分配的对象填充缓冲区的一半 (num_elements/2)。

实际上,您必须使用不同分配器的唯一原因是,如果您希望分配器使用与默认分配器不同的分配方案(它在系统中实际分配内存的方式)。