Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a const QString reference in case of failure?

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.

like image 692
moala Avatar asked Feb 28 '10 21:02

moala


People also ask

How do I check if QString is empty?

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.

How do you initialize QString?

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 .

What is QString in Qt?

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.


2 Answers

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?

like image 65
Ton van den Heuvel Avatar answered Oct 06 '22 02:10

Ton van den Heuvel


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
    }
}
like image 41
John Knoeller Avatar answered Oct 06 '22 04:10

John Knoeller