如何通过构造函数将容量大小传递给无锁 spsc_queue

How to pass capacity size to lock-free spsc_queue via constructor

我正在将 boost::lockfree::spsc_queue<T> queue 包装到一个 RingBuffer class 中,并希望能够在我的项目中使用这个 RingBuffer。但是我很难通过 class 构造函数将容量大小传递给队列。

RingBuffer.hh

template<class T>
class RingBuffer {
private:
    int capacity;
    boost::lockfree::spsc_queue<T> queue;

public:
    explicit RingBuffer(int size)
    {
        if(size < 2){
            capacity = 2;
        } else {
            capacity = size;
        }
        queue(capacity); // Error here. Not working in this way
    }

    ~RingBuffer()
    = default;

    int Insert(); // queue.push()
    int Extract(); // queue.pop()
}

在main.cpp

int main(int argc, char *argv[]) {

    auto ringBuffer = new RingBuffer<int>(3); // capacity size: 3 

    // ...
    // other things done
    // ...

    delete ringBuffer;
    return 0;
}

我希望这对我有用,但我收到错误消息: error: type 'boost::lockfree::spsc_queue<int>' does not provide a call operator。 @queue(capacity)在RingBuffer的构造函数里面。

那么,我该如何实现呢?

spsc_queue 的界面中没有 operator()(int)。现在您的编译器向 queue(capacity); 抱怨 - 这会在 queue 实例上调用 opearator()(int)

我假设您的意图是调用 spsc_queue 的 ctor 并将 capacity 作为参数。

因此添加辅助方法来计算此容量并将其传递给初始化列表上的队列构造函数:

template<class T>
class RingBuffer {
private:
    int capacity;
    boost::lockfree::spsc_queue<T> queue;

public:

    int getCapacity(int size) {
        if(size < 2){
            capacity = 2;
        } else {
            capacity = size;
        }
        return capacity;
    }

    explicit RingBuffer(int size)
      : queue( getCapacity(size) )  // call ctor on initialization list
    {

    }

    ~RingBuffer()
    = default;

    int Insert(); // queue.push()
    int Extract(); // queue.pop()
};

Demo