简体   繁体   English

发出完信号后QNetworkReply抛出SIGSEGV

[英]QNetworkReply throwing SIGSEGV when finished signal emitted

My application makes use of QNetworkReply 's for send and receiving data from a RESTful API. 我的应用程序使用QNetworkReply来从RESTful API发送和接收数据。

There are many tutorials available for using the QNetworkReply with QNetworkAccessManager 有许多可用于将QNetworkReplyQNetworkAccessManager结合使用的教程。

Once such example which I used can be found here or even here 我曾经用过的例子可以在这里甚至这里找到

Basic Usage: 基本用法:

// Header //标题

QNetworkAccessManager *manager;
QNetworkReply *myReply;
QMetaObject::Connection conReply;

// Making the request //发出请求

void MainWindow::makeRequest(QString url) {
    //...
    QNetworkRequest request(QUrl(url));
    myReply = manager->get(request) // or post(request)
    conReply = QObject::connect(myReply, SIGNAL(finished()), this,  SLOT(myReplyResponse()));
}

// Handling the request //处理请求

void MainWindow::myReplyResponse(){
    QObject::disconnect(conReply);

    QByteArray data = myReply->readAll();
    // or QByteArray data = myReply->read(myReply->bytesAvailable());

    myReply->deleteLater();

    // do something with this data

    //...
}

Using a similar implementation, I request data every X seconds. 使用类似的实现,我每X秒请求一次数据。

Problem: 问题:

When receiving the finished() signal, the code handling the reply is triggered, but when reading the data, I get a SIGSEGV . 当收到finished()信号时,触发处理应答的代码,但是在读取数据时,我得到了SIGSEGV

This issue seems to occur at random, thus I cannot determine what triggers it. 这个问题似乎是随机发生的,因此我无法确定触发它的原因。

Any suggestions would be gladly accepted. 任何建议都将很乐意被接受。

What is probably happening is that it is delaying the order, let's say that an order is sent every second but it takes 2 seconds to replicate, after 2 seconds you have read the reply and you have deleted it from memory, when the other comes myReply is an empty pointer. 可能正在发生的事情是延迟了订单,比方说每秒发送一次订单,但是复制需要2秒,在2秒钟后您已经阅读了答复并已将其从内存中删除,而另一个则是myReply是一个空指针。 What you must do is use sender() to obtain the replica, and it is always advisable to validate that you do not have an empty pointer: 您必须执行的操作是使用sender()获取副本,并且建议始终验证您没有空指针:

*.h *。H

private:
    QNetworkAccessManager *manager;

*.cpp *的.cpp

[...]
manager = new QNetworkAccessManager(this);
[...]
void MainWindow::makeRequest(const QString &url)
{
    Qurl mUrl(url);
    QNetworkRequest request(mUrl);
    QNetworkReply *myReply = manager->get(request); // or post(request)
    connect(myReply, &QNetworkReply::finished, this,  &MainWindow::myReplyResponse);
}

void MainWindow::myReplyResponse()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
    if(reply){
        QByteArray data = reply->readAll();
        qDebug()<<data;
        reply->deleteLater();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM