[ fromfile: functions.xml id: constreference ]
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"; m_Name = newName; } void setNameCR( const QString& newName) { // newName += " Python"; m_Name = newName; } void setNameR( QString& newName) { newName += " Dobbs"; m_Name = newName; } private: QString m_Name; }; int main() { Person p; QString name("Bob"); p.setNameCR(name); // p.setNameR("Monty"); p.setNameCR("Monty"); p.setNameV("Connie"); p.setNameR(name); qDebug() << name; }
Changes a temporary that's about to be destroyed. | |
Error: Can't change const&. | |
Changes the original QString. | |
No temporaries are created. | |
Error: Cannot convert to a QString&. | |
char* converts to temporary and gets passed by const reference. | |
Temporary QString #1 is created to convert char* to QString. Temporary #2 is created when it is passed by value. | |
No temporaries are created. |
Generated: 2012-03-02 | © 2012 Alan Ezust and Paul Ezust. |