0

I have encountered the following situation:

void Plugin::sendMessage(const QString& jid, const QString &message) {
    qDebug() << "SENDING TO JID1: " << jid;
    QtConcurrent::run([&, this]() {
        qDebug() << "SENDING TO JID2: " << jid;
    }
}

produces next output:

SENDING TO JID1: "test@xmpp.org"

SENDING TO JID2: "

and then it crashes. It looks like jid is no longer exists in the lambda, but why? How then can I use the variables by references in this code?

Community
  • 1
  • 1
VP.
  • 15,509
  • 17
  • 91
  • 161
  • 4
    The problem is most likely that you have no control over when the lambda function in the `QConcurrent` is executed, and that might mean that the string that is referenced by `jid` have been destructed. Capture by value instead. – Some programmer dude Jan 24 '15 at 12:19
  • Yes, it works if I capture by value, just wondered why compiler can't prolong existence of the reference until lambda execution. – VP. Jan 24 '15 at 12:25
  • 1
    Because the compiler have no idea what's happening, or when (if ever) the reference will be needed. – Some programmer dude Jan 24 '15 at 12:32
  • Okay, you may answer the question and I'll accept it. If you don't want too I may delete the question. – VP. Jan 24 '15 at 12:33

1 Answers1

0

If you are coming from Java background, note that references in C++ and Java mean something very different. In Java references are garbage collected and therefore it is easy to prolong their lifetime as needed. In C++ there is no garbage collection and a reference variable lifetime has little relation to the lifetime of the referenced object.

See also C++ References and Java References or Programmers Why do C++ and Java both use the notion of “reference” but not in the same sense? for some more explanation.

Community
  • 1
  • 1
Suma
  • 33,181
  • 16
  • 123
  • 191