Using a const QString & if a function returns a QString
Maybe this is a dumb question (maybe caused by lack of C++ knowledge), but I'm not sure if I have faulty reasoning about this:
When calling a function using e. g. a
QString, it seems to be reasonable to me to use (if possible) a
const QString &to call it so that no copy of the
QStringis passed to the function, but only a reference to the actual data. But what about a function returning a
I have e. g. the following code:
const QString text = jsonObject.value(someKey).toString(); someFunction(text); someOtherFunction(text);
The following works as well:
const QString &text = jsonObject.value(someKey).toString(); someFunction(text); someOtherFunction(text);
QString. So what is referenced in the second case? The return value of the function as long as it doesn't go out of scope? And is it better to do it in this way?
Thanks for all clarification!
what you found is Reference Lifetime Extension - so you referenced a QString.
However, as the Qt data classes implement implicit sharing, the first variant is the one you will see more often (and that is used within Qt itself also).
So … should I use
const QString text =or
const QString &text =? Are there any (dis)advantages of one version?
QStrings already do not work by copying as you assumed, e.g. from docs
Behind the scenes, QString uses implicit sharing (copy-on-write) to reduce memory usage and to avoid the needless copying of data.
so basically you can use const QString text and get sort of const QString &text effect.
This is as mentioned handled by the QString class and makes copying QStrings cheap as they
share the string data unless one of them modifies it. TL:DR version.. ;)
const is always good to use for +1 for that.
Thanks for the clarification :-)