I am always in a doubt on when I should reference and when I should use a variable pass. For example, one of the API is called by the JOBJECTs -
QLIST retrive_cinemas(QString& options)
{
return (staticobject::getcinemas(options));
}
or
QLIST retrive_cinemas(QString options)
{
return (staticobject::getcinemas(options));
}
It seems to me that your problem can be reduced to something like this:
You have a function/method
f(), and a classX, and you want to know if/whenXshould be passed tof()by reference or not.
You can identify three options:
void f(X v) // #1 - pass by value
void f(const X& cr) // #2 - pass by const reference (&)
void f(X& r) // #3 - pass by reference (&)
If X is cheap to copy (e.g. it's an int, a double, etc.),
and you do not want to modify it, then pass by value (#1).
If X is not cheap to copy (e.g. it's a vector, a string,
etc.), and yo do not want to modify it, then pass by const
reference (#2).
If you want to modify the argument of type X inside f(), then
pass by reference.
In the particular code you posted, since QString is a full-fledged class which is not cheap to copy as e.g. an int or a double (even if it uses COW techniques and "implicit sharing", I believe that copying still implies a call to something like Win32 InterlockedIncrement() for increasing the ref count in a thread-safe atomic way), I'd pass it by const reference (i.e. const QString &, #2) if you do not want to modify it inside the function.
Just pass by reference (QString&, #3) if you want to modify it inside the function's body.
In Qt the answer depends on whether the object you would like to pass uses implicit sharing or not:
Many C++ classes in Qt use implicit data sharing to maximize resource usage and minimize copying. Implicitly shared classes are both safe and efficient when passed as arguments, because only a pointer to the data is passed around, and the data is copied only if and when a function writes to it, i.e., copy-on-write.
You can but you need not pass objects using implicit sharing by reference. They are designed to be passed by value efficiently!
Here you can find the complete explanation and the list of classes using implicit sharing. QString uses implicit sharing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With