- Terminology: const Reference is a Reference to const
C++ programmers tend to abbreviate the phrase “reference to const” as“const reference.” This abbreviation makes sense—if you remember that itis an abbreviation.
Technically speaking, there are no const references. A reference is not anobject, so we cannot make a reference itself const. Indeed, because thereis no way to make a reference refer to a different object, in some sense allreferences are const. Whether a reference refers to a const or nonconsttype affects what we can do with that reference, not whether we can alterthe binding of the reference itself.
double dval = 3.14; int &r = dval; //illegal const int &ri = dval; //legal
It is important to realize that a reference toconstrestricts only what we can dothrough that reference.
int i = 42;
int&r1=i;// r1 bound to i const int &r2 = i;// r2 also bound to i; but cannot be used to change i
r1=0;// r1 is not const;i is now 0
r2 = 0;// error: r2 is a reference to const
-
low-level constis never ignored. When we copy an object,both objects must have the same low-levelconstqualification or there must be aconversion between the types of the two objects. In general, we can convert anonconsttoconstbut not the other way round.
To set “int *p = p3” illegal is to prevent inadvertently changing the value stored in p3 which is supposed to be const.const int *p = i; int *p1 = p; //illegal
const int *p = nullptr; // p is a pointer to a const int
constexpr int *q = nullptr; // q is a const pointer to int
constexpr const int *p = &i;
typedef double wages; // wages is a synonym for double typedef wages base, *p; // base is a synonym for double, p for double* using SI = Sales_item; // SI is a synonym for Sales_item
typedef char *pstring;
const pstring cstr = 0; // cstr is a constant pointer to char
const pstring *ps; //ps is a pointer to a constant pointer to charconst int ci = i, &cr = ci; auto b = ci; // b is an int (top-level const in ci is dropped) auto c = cr; // c is an int (cr is an alias for ci whose const is top-level) autod=&i; // d isan int*(& ofan int objectis int*) auto e = &ci; // e is const int*(& of a const object is low-level const)
If we want the deduced type to have a top-level const, we must say so explicitly:
const auto f = ci; // deduced type of ci is int; f has type const int