【问题标题】:Why have QString in struct sometimes a bad-ptr?为什么结构中的 QString 有时是 bad-ptr?
【发布时间】:2010-01-21 08:36:15
【问题描述】:

我遇到了一个复杂的错误。该软件将 PrintParamters 发送到打印机几次。在某个时刻,参数结构的所有 QStrings 都被破坏(坏 ptr)

Structs 中的 QString 是否存在一般问题?

这是我正在使用的结构:

typedef struct RecorderPrintParam {
  ES_DataType xxxxxxxxxx;
  bool  xxxxxxxxxxx;
  bool  xxxxxxxxxxxx;
  bool  xxxxxxxxxxxx;
  int      xxxxxxxxxxxxxxxxxxxxxx;
  double   xxxxxxxxxxxxxxx;
  double   xxxxxxxxxx;
  bool     xxxxxxxxxxx;
  int   xxxxxxxxxxxxxxx;
  double  xxxxxxxxxxx;
  bool     xxxxxxxxxxx;
  bool  xxxxxxxxxx;
  double  xxxxxxxxx;
  QString  xname;
  QString  yname;
  QString  anotherValue;
  QString  opername;
  QString  region;
  QString  application;
  QString  version;
  AxisUnit axUnit ;
  double  axLenM;
  double  xxxxxxxx;
  double  xxxxxxxx;

  int     xxxxxxxx;
  double  xxxxxxxxx;
  double  xxxxxxxxx;

  bool  xxxxxxxxxxxxxxx; /

  double  xxxxxxxxxxxxxxx;  

  double  xxxxxxxxxx;
  bool   xxxxxxxxx;

 }RecorderPrintParam;

以下是该结构的使用方式: 从 GUI 类调用:

void 
MyDlg::UpdateRecorderPrintParameters()
{
       RecorderPrintParam param;
       ....
       ....
       param.xname  = QString("abc def 123");
       _recorder->setParam(&param);
}

param.xname 已经有一个错误的 ascii ptr !! ? 我还尝试使用 just = "abc def 123" 而不是 = QString("abc def 123");但这是同样的错误发生

setParam 函数如下所示:

RecorderInterface::setParam(RecorderPrintParam *up)
{

....
...
if(up->xname.compare(_myParams.xname)!=0 ) _newHeaderPrint=true;
...
...
}

}

此时xname还有一个地址“8xname = {d=0x08e2d568 }”,但是xname.ascii有一个0x00000000指针

【问题讨论】:

  • 你还应该发布代码来展示你是如何使用这个结构的。例如是动态分配的吗?
  • 好的,我已经更新了我的帖子
  • 根据这些信息有什么想法吗?

标签: c++ qt struct qt3 qstring


【解决方案1】:

您正在堆栈中创建一个结构:RecorderPrintParam param 然后你把这个结构的地址传给另一个函数_recorder->setParam(&param);

UpdateRecorderPrintParameters 退出时param 超出范围并且其内容变为无效。在堆中分配它并在 GUI 使用它的值完成时释放它, 或将param按值传递给setParam

更新此代码以这种方式创建字符串还有一个问题:

QString("abc def 123"); 

创建一个临时对象,其引用由重载的QString = 运算符返回 C++ 标准说 (12.1)

临时绑定到引用 函数调用中的参数持续存在 直到全部完成 包含调用的表达式。

所以QString("abc def 123") 对象的析构函数在param 对象被传递给setParam 之前被调用

尝试将 QString("abc def 123") 更改为 QString str("abc def 123"); 和param.xname = str;param.xname = "abc def 123"

【讨论】:

  • 我已经测试过按值传递参数,但它会导致相同的错误:(
  • param.xname = "abc def 123" ->我已经对此进行了测试,这导致了同样的错误..我也这么认为.....
  • 我能想到的唯一其他解释是您的代码的其他部分正在破坏堆栈。
  • 据我所知,我不明白您更新后的部分:RecorderPrintParam param; param.xname = QString("abc def 123"); _recorder->setParam(&param);如果我正确理解您的评论,则此代码 sn-p 有问题???
猜你喜欢
  • 2014-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-28
相关资源
最近更新 更多