When modifying with
const, there are three different effects depending on the position ofconst.The criterion is: whatever
constmodifies, the content of that thing (afterconst) is immutable.
Modifying variables
const int a; means the variable cannot be changed.
Modifying pointers
Divided into pointers to constants (pointer to const) and pointers that are themselves constants (constant pointer, const pointer).
const int *p = &a;
*p is immutable. *p is the content of the memory location pointed to by p, so *p being immutable means the content of the memory location pointed to by p is immutable. p is mutable, meaning the memory location (variable) pointed to by p can be changed, but whatever p points to, that value is immutable.
| |
int* const p = &a;
const modifies p, so the pointer p is immutable, meaning the memory location pointed to by p cannot be changed. The pointing of p is immutable, but the content of the memory location pointed to by p can change.
| |
const int* const p = &a;
const modifies both *p and p, so both the memory location pointed to by p and the content of the memory location pointed to by p are immutable.
| |
Modifying references
A reference to a constant (reference to const), used for parameter types, which avoids both copying and modification of the value by the function;
| |
The purpose of a const reference is to prohibit changing the referenced object by modifying the reference value.
There is no const reference, because a reference itself is a const pointer.
- An ordinary reference is equivalent to
int* const e const int &eis equivalent toconst int* const e
Modifying member functions
Indicates that member variables cannot be modified within this member function.
- A member function modified with
constcan only read data members; a member function withoutconstcan read and write data members. - A
constobject can callconstmember functions and cannot call functions not modified withconst.
| |
This is equivalent to C++ hiding the this pointer in the class’s member functions. In essence, const modifies the memory space pointed to by the hidden this pointer; it modifies the this pointer (const Class *this).