使用带有分配器的 boost::lockfree::spsc_queue

Using boost::lockfree::spsc_queue with an allocator

本文关键字:lockfree spsc queue boost 分配器      更新时间:2023-10-16

以下是我问题的表示。

#include <boost/lockfree/spsc_queue.hpp>
class test {
  struct complicated {
    int x;
    int y;   
  };
  std::allocator<complicated> alloc;
  boost::lockfree::spsc_queue<complicated, 
    boost::lockfree::allocator<std::allocator<complicated> > > spsc;
  test(void);
}; 
test::test(void): spsc( alloc ) {};

使用此代码,我在VS2010中遇到以下错误:

错误 C2512:"提升::无锁定::d尾巴::runtime_sized_ringbuffer":没有可用的适当默认构造函数

编译类模板成员函数 'boost::lockfree::spsc_queue::spsc_queue(const std::allocator<_Ty> &)'

错误消息指出它正在编译一个带有一个参数的构造函数,我认为它应该是分配器,但主要错误涉及默认构造函数。

文档的起点是 http://www.boost.org/doc/libs/1_54_0/doc/html/lockfree.html。

定义 boost::lockfree::spsc_queue 和 boost::lockfree::分配器的适当机制是什么?

根据 boost 源代码,由于您没有为spsc_queue指定编译时容量,因此spsc_queue的基类通过 typedefs 和模板魔术解析为具有以下构造函数runtime_sized_ringbuffer

explicit runtime_sized_ringbuffer(size_t max_elements);
template <typename U>
runtime_sized_ringbuffer(typename Alloc::template rebind<U>::other const & alloc, size_t max_elements);
runtime_sized_ringbuffer(Alloc const & alloc, size_t max_elements);

如您所见,所有这些构造函数都需要一个max_element参数。提供此功能的唯一方法是使用以下spsc_queue构造函数之一:

explicit spsc_queue(size_type element_count):
    base_type(element_count)
{
    BOOST_ASSERT(runtime_sized);
}
template <typename U>
spsc_queue(size_type element_count, typename allocator::template rebind<U>::other const & alloc):
    base_type(alloc, element_count)
{
    BOOST_STATIC_ASSERT(runtime_sized);
}
spsc_queue(size_type element_count, allocator_arg const & alloc):
    base_type(alloc, element_count)
{
    BOOST_ASSERT(runtime_sized);
}

换句话说,尝试在调用spsc_queue构造函数时提供大小和分配器。