Qt parallel start, transfer value by reference, but the memory address is different?

I use QtConcurrent::runto run the function and pass the value by reference, but the memory address of the value is different.

But if I pass the value by pointer, then the address will be the same! I can not understand. Did I miss something?

Here is the code.

void ptr(QString* s)
{
    qDebug() << "pass by ptr: " << s;
}

void ref(QString& s)
{
    qDebug() << "pass by ref: " << &s;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QString str;
    QFuture<void> f1 = QtConcurrent::run(ptr, &str);
    f1.waitForFinished();

    QFuture<void> f2 = QtConcurrent::run(ref, str);
    f2.waitForFinished();

    qDebug() << "address of str: " << &str;

    return a.exec();
}

Conclusion:

pass by ptr:  0x28fefc
pass by ref:  0x525de4
address of str:  0x28fefc
+4
source share
2 answers

QtConcurrent::runcreates internal copies of all arguments that you pass to it. Then, your stream function is granted access to these copies, and not to the original arguments. Passing something by reference does not prevent the creation of a copy. In other words, QtConcurrent::runinternally implements the semantics of pass-by-value.

, ref, .

, , - "-".

+9

/ , std:: ref. :

#include <functional>
...

QFuture<void> f2 = QtConcurrent::run(ref, std::ref(str));
+4

All Articles