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

moala picture moala · Feb 28, 2010 · Viewed 7.3k times · Source

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.

Answer

Ton van den Heuvel picture Ton van den Heuvel · Feb 28, 2010

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?