A const reference is a reference to a const object.
Copy codeThe Code is as follows: const int I = 10;
Const int & ref = I;
You can read the ref but cannot modify it. This makes sense, because I itself cannot be modified, and of course it cannot be modified through ref. Therefore, it is invalid to assign the const variable to a non-const reference.Copy codeThe Code is as follows: int & ref1 = I; // error: nonconst reference to a const object
A non-const reference is a reference to a non-const type variable.
Const references can be initialized to different types of objects or right values (such as literal constants), but non-const references cannot.Copy codeThe Code is as follows: // legal for const references only
Int I = 10;
Const int & ref = 42;
Const int & ref1 = r + I;
Double d = 3.14;
Const int & ref2 = d;
Take binding to different types of ref2 as an example to explain the cause. The compiler will convert the ref2-related Code as follows:Copy codeThe Code is as follows: int temp = d;
Const int & ref2 = temp; // bind ref2 to temporary
Ref2 is actually bound to a temporary variable. If ref2 is not a const, you can modify the value of d by modifying ref2, but actually d will not change. To avoid this problem, ref2 can only be a const.
Non-const references can only be bound to objects of the same type as the reference. const references can be bound to objects of different but related types or to the right value.