5.6.  References to const

[ fromfile: functions.xml id: constreference ]

Declaring a reference parameter to be const tells the compiler to make sure that the function does not attempt to change that object. For objects larger than a pointer, a reference to const is an efficient alternative to a value parameter because no data is copied. Example 5.14 contains three functions, each accepting a parameter in a different way.

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.

<include src="src/const/reference/constref.cpp" href="src/const/reference/constref.cpp" id="constrefcpp" mode="cpp"/>