Search code examples
c++qtqt4constantsqstring

Proper usage/modification of QString given that some functions are const and others non-const


I am performing some operations on a QString to trim it down, but I don't want to affect the original string. I am new to Qt and am confused about the proper way to use the various QString functions, since some are const, and others are not. So far, this is what I have:

// this needs to be const so it doesn't get modified.
// code later on is depending on this QString being unchanged
const QString string = getString();

The methods I need to call are QString::simplified(), QString::remove(), and QString::trimmed(). The confusing part is what is the correct way to do this given that simplified() and trimmed() are const, but remove() is not. Keeping in mind that I to copy the original and make modifications directly to the copy, this is what I have:

// simplified() is a const function but no problem because I want a copy of it
QString copy = string.simplified(); 

// remove is non-const so it operates on the handle object, which is what I want
copy.remove( "foo:", Qt::CaseInsensitive );

// trimmed() is const, but I want it to affect the original
copy = copy.trimmed();

Is using copy = copy.trimmed() the right way to handle this case? Will this accomplish my goal of having copy be trimmed() for the next usage? Is there a better (more elegant, more efficient, more Qtish) way to do this?

I have checked the QString Qt Documentation and was not able to satisfactorily answer these questions.


Solution

  • I think the answer is simply for optimization reasons.

    Behind the scenes, QString uses implicit sharing (copy-on-write) to reduce memory usage and to avoid the needless copying of data. This also helps reduce the inherent overhead of storing 16-bit characters instead of 8-bit characters.

    Often times I'll tack on a few different ones when they are returning a reference to the modified string to get an end result. (The more elegant way...)

    For example:

    QString str = " Hello   World\n!";
    QString str2 = str.toLower().trimmed().simplified();
    if(str2.contains("world !"))
    {
        qDebug() << str2 << "contains \"world !\"";
    }
    

    Here is more on implicit sharing:

    http://qt-project.org/doc/qt-4.8/implicit-sharing.html

    Hope that helps.