I am trying to figure out how to use the following constructor for boost::circular_buffer:
circular_buffer(capacity_type buffer_capacity, size_type n, const_reference item, const allocator_type& alloc = allocator_type());
I have a custom class:
template<class T> class Custom
{
public:
Custom() :
time(0.0)
{}
double time;
T data_;
};
With my circular buffer defined using the constructor taking in just a capacity:
boost::circular_buffer<Custom<T>> buffer(10);
I have not worked much with allocators, and I want to initialize my buffer with default/empty/zero values at construction, and it seems that the constructor mentioned above is the way to go about it using boost::circular_buffer, however I am not exactly sure how to with boost constructor. If it were an ordinary vector I assume I can do the following:
int num_elements = 10;
Custom<T> custom;
std::vector<Custom<T>> buffer(10, custom);
I could not really find any examples on this specifically, so any help or guidance is appreciated.
Just like your std::vector
call where you do not specify an allocator for Custom
and use the default, you can do the same thing with boost::circular_buffer
. The only difference is boost::circular_buffer
has an extra parameter allowing you set the capacity and number of default constructed objects in the buffer at the same time. That means if you want a full boost::circular_buffer
then you would use:
int num_elements = 10;
Custom<T> custom;
boost::circular_buffer<Custom<T>> buffer(num_elements, num_elements, custom);
Which give you a boost::circular_buffer
with a capacity of num_elements
with num_elements
default allocated objects in it.
You could also have:
boost::circular_buffer<Custom<T>> buffer(num_elements, num_elements/2, custom);
Which sets the capacity to num_elements
but only fills half the buffer (num_elements/2
) with default allocated objects.
Really the only reason you would have to use a different allocator is if you want the allocator to use a different allocation scheme (how it actually allocates memory in the system) than the default.