5.6.  References to const

[ fromfile: functions.xml id: constreference ]

Example 5.14. src/const/reference/constref.cpp

#include <QtCore>

class Person {
public:
    void setNameV( QString newName) {
        newName += " Smith";                1
        m_Name = newName;
    }
    void setNameCR( const QString& newName) {
//      newName += " Python";               2
        m_Name = newName;
    }
    void setNameR( QString& newName) {
        newName += " Dobbs";                3
        m_Name = newName;
    }
private:
    QString m_Name;
};

int main() {
    Person p;
    QString name("Bob");
    p.setNameCR(name);                      4 
//  p.setNameR("Monty");                    5
    p.setNameCR("Monty");                   6
    p.setNameV("Connie");                   7
    p.setNameR(name);                       8
    qDebug() << name;         
}

1

Changes a temporary that's about to be destroyed.

2

Error: Can't change const&.

3

Changes the original QString.

4

No temporaries are created.

5

Error: Cannot convert to a QString&.

6

char* converts to temporary and gets passed by const reference.

7

Temporary QString #1 is created to convert char* to QString. Temporary #2 is created when it is passed by value.

8

No temporaries are created.