1. const reference
1. Non-const reference, can only be bound to objects of the same type;
1.2.const reference: How can I bind a reference to an object of different but related types or to the right value;
double a = 3.14;const int &b = a; //right
2. Const and iterator
2.1. const_iterator: Read-Only elements in the container;
for(vector<string>::const_iterator iter = text.bgin(); iter != text.end(); ++iter)cout<<*iter<<endl; //right*iter=" "; //wrong
2.2. If const and iterator are used together, it means that the iterator cannot be modified, but the content can be;
vector<int> num(10);const vector<int>::iterator iter = num.begin();*iter=1; //right++iter; //wrong
2.3. Any operation that changes the vector will invalidate the existing iterator, for example, push_back.
3. Const and pointer
3.1 pointer to the const object
const double *cptr;
* Cptr = 42; // error: you cannot modify the value of the object you refer to through cptr, but you can point it to another const object const double Pi = 3.14; double * PTR = PI // error: PTR is a common pointer const double * cptr = & PI // right: cptr is a pointer to a const object
You cannot use the void * pointer to save the address of the const object. Instead, you must use the const void * pointer to save the address of the const object.
const int universe = 42;const void *cpv = &universe: //rightvoid *pv = &universe;//wrong
Allow non-const object addresses to be assigned to const object pointers
Double dval = 3.14; cptr = & dval; // OK: However, any behavior that modifies the value through cptr will cause compilation errors.
The pointer pointing to the const can be understood as "the pointer pointing to the const itself"
3.2 const pointer (cannot be modified)
Int num = 0; int * const num_constp = & num; // num_constp is the const pointer.
Any assignment to the const pointer (even with the same value) results in compilation errors (like any const volume, the const pointer must be initialized at definition ):
Num_constp;//error
The value of the object to which the Pointer Points can be modified.
* Num_constp = 0; // right; as long as it conforms to the object type
3.3 const pointer to the const object (cannot be changed)
const double pi = 3.14; const double *const pi_ptr = &pi
3.4Typedef and const pointers
const pstring cstr;
What type is CSTR?
Const string * CSTR; // wrong; Because const modifies a type; srting * const CSTR; // right
It is hard to understand because the position of the const qualifier can be placed before or after the type;
String const S1; const string S2; // they are of the same type
For typedef
String s; typedef string * pstring; // The const pointer to the string type. Const pstring cstr1 = & S; pstring const cstr2 = & S; // easy to understand string * const cstr3 = & S;