0

I have a simple class that looks like this:

class QNetworkAccessManager;

class FontiDownloader : public QObject
{
    Q_OBJECT
public:
    FontiDownloader(QNetworkAccessManager* netManager);

    void downloadFonti();
private:
    QString m_dataLocation;
};

The implementation of downloadFonti() is something like the following:

    // the networkrequest is just a wrapper that makes a QNetworkRequest
    auto nr = new NetworkRequest(m_netManager, this);

    connect(nr, &NetworkRequest::completed, [this](QNetworkReply* reply){
        // crash occurs here
        QString dataLocation = m_dataLocation;
    });
    nr->send(QUrl(FONTI_URL), HttpMethod::GET);

When I call my lambda function inside downloadFonti(), the program crashes and I have located the reason to be the line:

    QString dataLocation = m_dataLocation;

I can see using the debugger that at the time of calling that line, m_dataLocation is "not accessible". However, I cannot think why this would be the case.

reckless
  • 741
  • 12
  • 53
  • 2
    Without a [mcve] I can only guess but it sounds like the `FontiDownloader` referred to by `this` is no longer valid (i.e. has been destructed) when the lambda is invoked. Hence it's undefined behaviour. – G.M. Apr 05 '20 at 08:31
  • @G.M. Although I agree with the MRE, I don't think that what you signal could be the cause of the problem since not using "QObject::connect" then it follows that "connect" belongs to "this" so if the object then the connection will be removed, so the lambda will not be invoked. – eyllanesc Apr 05 '20 at 12:38
  • @eyllanesc I initially thought the same but it doesn't appear that's the case. With the `connect` call shown -- without any QObject receiver context -- the lambda is essentially 'detached' and will be called regardless of the validity of the `this` pointer. The connection is not automatically removed. If, on the other hand, the `connect` call is changed to `connect(nr, &NetworkRequest::completed, this/* receiver context */, [this](QNetworkReply* reply)...` then the connection *is* automatically removed as expected. I'll check again. Still need that [mcve] though. – G.M. Apr 05 '20 at 13:11
  • @G.M. I will try to come up with a MRE although at the moment I haven't been successful in reproducing the problem outside my project – reckless Apr 05 '20 at 15:13

0 Answers0