C++ 为什么我的队列类中的std::queue不是空的?

C++ 为什么我的队列类中的std::queue不是空的?,c++,c++14,C++,C++14,为什么我的队列类中的std::queue不是空的 每次初始化队列时,它在构造函数中为空,但在调用类方法size()时返回非零大小 这里是一个MWE: / TEST QUEUE #include<iostream> #include<queue> #include<mutex> #include<condition_variable> #include <Eigen/Dense> template <class dtype>

为什么我的队列类中的
std::queue
不是空的

每次初始化队列时,它在构造函数中为空,但在调用类方法size()时返回非零大小

这里是一个MWE:

/ TEST QUEUE
#include<iostream>
#include<queue>
#include<mutex>
#include<condition_variable>

#include <Eigen/Dense>

template <class dtype> 
class Queue {
    private:
    std::queue<dtype> q;
    std::mutex qmtx;
    std::condition_variable qcond;

    bool start = false; 
    bool display = false;
    public:
    Queue(bool sstart, bool qdisplay) : start(sstart), display(qdisplay) 
    {
        std::clog << "In q constructor: " << q.size() << std::endl;
    }

    // Method to push values on to queue
    void push(const dtype & message); 
    dtype pop(); 
    void stop();
    bool empty();
    bool size();
    bool clear();
};
/测试队列
#包括
#包括
#包括
#包括
#包括
模板
类队列{
私人:
std::队列q;
std::互斥qmtx;
std::条件变量qcond;
bool start=false;
布尔显示=假;
公众:
队列(bool-sstart,bool-qdisplay):开始(sstart),显示(qdisplay)
{

std::clog
size
不应该返回
bool
。好吧。但是为什么我没有得到编译错误?@fatm您的代码有未定义的行为,因为您的函数假设返回
bool
,但不返回任何内容。因此,在修复这些错误并重新运行程序之前,无法对代码进行推理。是否
size
应该返回一个
bool
是另一个独立的问题——现在,程序基本上是无用的,除非你从那些函数中实际返回一些东西。啊,甚至更糟。

template<typename dtype>
dtype Queue<dtype>::pop() {
    std::unique_lock<std::mutex> lock(qmtx);
    qcond.wait(lock, [&]() { return !q.empty() | start; } );

    if (!start) {
        std::clog << "The queue has stopped popping." << std::endl;
    }

    dtype ret = q.front();
    q.pop();

    return ret;
}

// Method to push values on to queue
template<typename dtype>
void Queue<dtype>::push(const dtype & message) {
    std::unique_lock<std::mutex> lock(qmtx);
    if (display) { std::clog << "Qpush Locked." << std::endl; }
    q.push(message);
    qcond.notify_one();
}

template<typename dtype>
void Queue<dtype>::stop() {
    start = false;
    qcond.notify_all();
}

template<typename dtype>
bool Queue<dtype>::empty() {
    std::unique_lock<std::mutex> lock(qmtx);
    q.empty();
}

template<typename dtype>
bool Queue<dtype>::size() {
    std::unique_lock<std::mutex> lock(qmtx);
    q.size();
}

template<typename dtype>
bool Queue<dtype>::clear() {
    std::unique_lock<std::mutex> lock(qmtx);
    std::queue<dtype> empty;
    std::swap(q, empty);
}

int main () {
    Queue<Eigen::VectorXd> YQ(false, false);
    std::cout << YQ.size() << std::endl;
}