FAQ 11.06 What does it mean to return a reference?

The function call expression is an lvalue to the referent.

When a function returns a reference, the function call becomes an lvalue (see FAQ 11.04) for the referent. This is normally used to allow operator expressions (such as the subscript operator, the dereference operator, and so on) to be used as lvalues. The following example shows how returning a reference allows a subscript operator to be an lvalue.

 #include <iostream> #include <stdexcept> using namespace std; class Array { public:   float& operator[] (unsigned i) throw(out_of_range); protected:   float data_[100]; }; inline float& Array::operator[] (unsigned i) throw(out_of_range) {   if (i >= 100u)     throw out_of_range(" Array index is out of range");   return data_[i]; } int main() {   Array a;   for (unsigned i = 0; i < 100; ++i)     a[i] = 3.14 * i;   for (unsigned j = 0; j < 100; ++j)     cout << a[j] << '\n'; } 

Returning a reference to data_[i] doesn't return a copy of data_[i]; it returns data_[i] itself. Therefore, anything done to the expression in the caller (a[i]) is actually done to data_[i]. In the example, the statement a[i] =...actually changes data_[i] within object a.

C programmers should note that this allows a function call to appear on the left side of an assignment operator.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net