3.3 const reference

Let us now consider the following example:

void f(const int &i)
{
  cout << i << endl;
}

void test(void)
{
  f(123);
}

At first glance, this code should generate an error because parameter i of f is pass-by-reference. However, 123 is a constant, which does not specify any storage to be passed by reference. To our surprise, there is no compile-time error!

The reason that there is no error is because the expression $123$ does evaluate to a constant value of $123$. However, in order for this constant value to be useful for anything, it must exist as a value in memory (on the stack, usually). In other words, the expression $123$ does have a nameless storage. That's why it can still be passed by reference.

The following code generates an error message:

void f(const int &i)
{
  i = i + 1;
}

This is because const int &i says that ``i is a reference to a const int''. This means that whatever i refers to cannot be changed.

Parameters of the type const SomeType & is used very often to pass large objects efficiently. Although a reference is not a pointer, passing an object by reference generates the same code as passing the address of the object. This means const SomeType & is often more efficient than const SomeType, especially when SomeType is a complex class with lots of data members.

Copyright © 2006-09-19 by Tak Auyeung