【问题标题】:Why does my program halt when calling front() on a std::queue?为什么我的程序在 std::queue 上调用 front() 时会停止?
【发布时间】:2011-10-14 13:32:11
【问题描述】:

我想在 Irrlicht 游戏中使用 Irrnet 网络库。

源代码使用 Linux 套接字,我正在尝试将其移植到 Windows 上,将其替换为使用 Windows 的 Winsock2 的代码。

库编译成功,但是当我尝试运行 Quake 示例时它崩溃了。我找到了程序停止的那一行,但我不知道如何解决这个问题。

程序在第二次调用函数getNextItem

时停止
class NetworkType {
    public :
        NetworkType();
        ~NetworkType();
        template<class T>
        void getNextItem(irr::core::vector3d<T>& data);

    private:
        typedef std::queue<std::string> Container;
        Container items;
};

template<class T>
void NetworkType::getNextItem(irr::core::vector3d<T>& data) {
    T X, Y, Z;

    std::istringstream item(items.front());
    // the program does not get here the second time it calls this function
    items.pop();

    item >> X;
    item >> Y;
    item >> Z;

    data = irr::core::vector3d<T>(X, Y, Z);
}

正好在这一行

  std::istringstream item(items.front());

谁能告诉我为什么程序第二次到达这一行时会停止?

这里是完整源代码的link

【问题讨论】:

  • 这似乎与游戏开发无关,可能更适合 StackOverflow;我已将问题标记为迁移考虑。
  • 断言(!items.empty());你应该总是编码你的假设。

标签: networking libraries irrlicht


【解决方案1】:

我认为“停止”是指某种方式的“崩溃”?有问题的线路崩溃的可能原因是:

  • 调用getNextItem() 方法的NetworkType 实例是垃圾(this 指针是垃圾或空)。这可能是由于其他地方的指针数学错误、实例的过早删除或破坏等原因而发生的。当程序尝试访问 items 成员时,这将表现为错误。
  • items 容器为空。在这些情况下,front() 的返回值是未定义的(因为它是一个引用),istringstream 的构造函数可能会崩溃。 front() 本身也可能引发调试/运行时检查错误,具体取决于您的编译器及其配置。

【讨论】:

  • 是的,“停止”是指“崩溃”。这里是 Irrnet link 的源代码链接。这可能有助于找到确切的原因。
【解决方案2】:

实际上,如果 dequeue 为空,您可能会遇到运行时错误:MSDN deque

因此,在尝试从中弹出值之前,只需检查双端队列是否为空。

if(items.size()>0)
{
//do things
}
else
{
 //error deque empty
}

[edit] 混淆了 std 和(我猜)MSDN(OP 没有说)lib。

【讨论】:

  • 我终于发现队列是空的,因为返回它的recvfrom没有成功。
  • 这个答案是错误的并且混淆了frontbegin。如果向量为空,front 未定义。乔希的回答涵盖了这一点。
  • (编辑错字)是的,你是对的,我猜是 MSDN 库,我将 stl 库(甚至没有“前”)混淆了。 stl::deque 使用 pop_front() 并按照我所说的工作,但我改变了答案。
  • std::deque 是 C++ 标准库的一部分; MS 的实现与大多数其他实现一样,具有frontbegin。问题实际上是关于 std::queue 适配器,它也在 stdlib 中,并且有一个 front 但没有 begin 也没有 end 也没有 push_front,因为队列是单向的。
猜你喜欢
  • 2021-07-01
  • 2021-01-09
  • 2015-12-13
  • 2017-04-12
  • 1970-01-01
  • 2013-10-17
  • 1970-01-01
  • 1970-01-01
  • 2011-11-13
相关资源
最近更新 更多