Reputation: 4840
I would like to know what is the most efficient and practical way of sending a Qstring as a parameter to a function, in QT more specifically. I want to use a reference. The problem is I also want to instantiate that string in the function itself like so for example:
this is the function prototype:
void myFunction(QString & theMsg);
this is the function call:
myFunction(tr("Hello StringWorld"));
now the function tr()
returns a QString but it doesn't work with a reference(I can see why).
I have to do this:
QString theQstr("Hello StringWorld");
myFunction(theQstr);
Is there a simpler way to do this while still using references or could I just change the function parameter to use a QString and it would still be efficient?
Upvotes: 23
Views: 17177
Reputation: 442
When you pass a QString, the call site has to call QString copy ctor then a dtor: both implies an atomic reference counting operation (not neglectable), and some more generated assembly code. Hence slower and bigger code (I don't mention here the less common std::move scenario).
On the other hand, when you pass a const QString&, on the called site, there is a double indirection to access the characters: a pointer to a pointer. Hence this is slower than passing a QString, especially if the QString parameter is much used.
I would recommend to always pass a const QString&, and if you need maximum speed on the called side, make a QString copy there, and access this local copy to avoid a double-indirection (faster, less generated code).
Upvotes: 2
Reputation: 7787
The most efficient and practical way is using a const reference. The QString COW will be slower than pass by reference but faster than a regular copy.
Upvotes: 10
Reputation: 903
QString uses COW (Copy On Write) behind the scenes, so the actual string isn't copied even if you use a signature like this:
void myFunction(QString theMsg)
(until you modify it that is).
If you absolutely want a reference I would use a const& unless you plan to modify the input argument.
void myFunction(QString const& theMsg)
Upvotes: 16