const 引用是指向 const 對象的引用:
const int ival = 1024; const int &refVal = ival; // ok: both reference and object are const int &ref2 = ival; // error: non const reference to a const object
可以讀取但不能修改 refVal ,因此,任何對 refVal 的賦值都是不合法的。這個限制有其意義:不能直接對 ival 賦值,因此不能通過使用 refVal 來修改 ival。
同理,用 ival 初始化 ref2 也是不合法的:ref2 是普通的非 const 引用,因此可以用來修改 ref2 指向的對象的值。通過 ref2 對 ival 賦值會導致修改 const 對象的值。爲阻止這樣的修改,需要規定將普通的引用綁定到 const 對象是不合法的。
const 引用可以初始化爲不同類型的對象或者初始化爲右值(第 2.3.1 節),如字面值常量:
int i = 42; // legal for const references only const int &r = 42; const int &r2 = r + i;
總結:const引用可以用於連接const和非const對象,非const引用只能連接非const對象。也表明了權限只能越來越嚴格,不能越來越鬆。