[ 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 <QString> 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; }; #include <qstd.h> using namespace qstd; int main() { Person p; QString name("Bob"); p.setNameCR(name);
// p.setNameR("Monty");
p.setNameCR("Monty");
p.setNameV("Connie");
p.setNameR(name);
cout << 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: $Date: 2009-09-08 12:15:32 -0400 (Tue, 08 Sep 2009) $ | © 2009 Alan Ezust and Paul Ezust. |