consider the following code:
const QString& MyClass::getID(int index) const
{
if (i < myArraySize && myArray[i]) {
return myArray[i]->id; // id is a QString
} else {
return my_global_empty_qstring; // is a global empty QString
}
}
How can I avoid to have an empty QString without changing the return type of the method? (It seems that returning an empty QString allocated on the stack is a bad idea)
Thanks.
QString() creates a string for which both isEmpty() and isNull() return true . A QString created using the literal "" is empty ( isEmpty() returns true ) but not null ( isNull() returns false ). Both have a size() / length() of 0.
Generally speaking: If you want to initialize a QString from a char*, use QStringLiteral . If you want to pass it to a method, check if that method has an overload for QLatin1String - if yes you can use that one, otherwise fall back to QStringLiteral .
The QString class provides an abstraction of Unicode text and the classic C '\0'-terminated char array. More... All the functions in this class are reentrant when Qt is built with thread support.
You can't. Either do not return a const reference or use a local static variable like this:
const QString& MyClass::getID(int index) const {
if (i < myArraySize && (myArray[i] != 0)) {
return myArray[i]->id; // id is a QString
}
static const QString emptyString;
return emptyString;
}
The advantage of this method over the other proposed methods is that this solution does not require a change to the interface of MyClass
. Furthermore, using a default parameter might confuse users of your class and lead to wrong class usage. This solution is transparent to the user.
By the way, are you really using a C style array in your class?
Since this is expected to return a const
value I see no problem with having a global (or static const) empty QString that is used by all such functions to return a an empty string.
I'm not wild about the name though. I would expect that the "empty" QString would be a static const member of the QString Class. so your code would look like this instead.
const QString& MyClass::getID(int index) const
{
if (i < myArraySize && myArray[i]) {
return myArray[i]->id; // id is a QString
} else {
return QString::EmptyString; // is a global empty QString
}
}
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