【问题标题】:qDebug() affects the result of program execution [closed]qDebug() 影响程序执行的结果[关闭]
【发布时间】:2021-07-05 06:42:25
【问题描述】:
int ICOperator::ICStarts( const char *port )
{
    if ( NULL == OpenReader) { qDebug() << ""; }

    this->devNo = this->OpenReader( 0, sPort );

    return this->devNo;
}

如函数所示,qDebug()并没有真正执行,但程序会崩溃,如果注释如下:

int ICOperator::ICStarts( const char *port )
{
  //  if ( NULL == OpenReader) { qDebug() << ""; }

    this->devNo = this->OpenReader( 0, sPort );

    return this->devNo;
}

在 qDebug() 中会发生什么?可能会出现堆栈错误?

【问题讨论】:

  • 两个sn-ps中哪个会导致崩溃?这不是很清楚。也请花一些时间阅读the help pages,阅读SO tour,阅读How to Ask,以及this question checklist。最后请学习如何创建minimal reproducible example,以及如何edit 来改进您的问题。
  • 顺便说一下,如果OpenReader 是成员函数(而不是变量),那么获取指向它的指针的正确方法是使用指向运算符&amp;。此外,NULL 在 C++ 中不推荐用于空指针,并且已经存在很长时间了。使用 nullptr(或 0 用于 C++11 之前的编译器)。
  • 顺便问一下,OpenReader 到底是什么?再次,请edit 向我们展示minimal reproducible example 的问题(强调最小 部分)。

标签: c++ qt crash stack qdebug


【解决方案1】:

您的应用程序崩溃不是因为您正在使用调试,而是因为您的逻辑并未避免使用无效指针。

如果 OpenReader 为 NULL,那么这是无效的 OpenReader( 0, sPort )

int ICOperator::ICStarts( const char *port )
{
    if ( NULL == OpenReader)
    { 
         qDebug() << "Invalid OpenReader";
         return -1; 
    }

    this->devNo = this->OpenReader( 0, sPort );
    return this->devNo;
}

【讨论】:

  • throw 例外——但这确实是正确答案。 qDebug 可能会完全改变程序失败的方式,但这不是失败的原因。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多