我必须将一个项目从 QT5 降级到 QT4,并在这样做时遇到奇怪的缓冲区溢出错误。这是我的代码:
我这样创建一个 QThread:
thread = new QThread;
reader = new Reader();
reader->setParams(samplingRate);
reader->moveToThread(thread);
connect(thread, SIGNAL(started()), reader, SLOT(read()));
connect(reader, SIGNAL(finished()), thread, SLOT(quit()));
connect(thread, SIGNAL(finished()), this, SLOT(threadFinished()));
connect(reader, SIGNAL(finished()), reader, SLOT(deleteLater()));
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
connect(reader, SIGNAL(errorMsg(QString)), this, SLOT(threadErrorMsg(QString)));
thread->start();
在我的线程中,我有以下代码:
try {
while(condition) {
...something
}
} catch(Exception e) {
emit errorMsg("Error");
}
emit finished();
我的主线程中的插槽是这样的:
void MainWindow::threadFinished() {
reader = NULL;
delete thread;
thread = NULL;
}
void MainWindow::threadErrorMsg(QString message) {
QMessageBox::critical(this, "Error", ("Error: " + message).toStdString().c_str(), QMessageBox::Ok);
}
所有这些在 QT5 中运行良好。错误消息框显示正确,线程被销毁。然而,在 QT4 (4.8.1) 中,当发生错误并发出 errorMsg() 时,我会收到缓冲区溢出错误。如果我不发出 errorMsg("Error") 并仅通过调用 finished() 销毁线程,则不会发生缓冲区溢出。关于这里出了什么问题的任何想法?
更新: 如果我不访问 threadErrorMsgit 中的 QString 确实有效。像这样:
void MainWindow::threadErrorMsg(QString message) {
QMessageBox::critical(this, "Error", "Error", QMessageBox::Ok);
}
我做错了什么?
最佳答案
void MainWindow::threadFinished() {
reader = NULL;
delete thread;
thread = NULL;
}
不建议直接删除插槽中的线程。您应该使用 deleteLater 函数。
thread->deleteLater();
但是,您已经设置了要在连接中删除的线程
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
所以你现在试图删除它两次!
至于缓冲区溢出,我怀疑在错误发生之前有什么东西损坏了内存。
关于c++ - 使用 Qt 线程和信号的缓冲区溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34675051/