C++ const references and non const references
- 2020-04-01 21:34:05
- OfStack
A const reference is a reference to a const object.
Ref can be read, but not modified. This makes sense, because I itself cannot be modified, and of course cannot be modified by ref. So it is illegal to assign a const variable to a non-const reference.
A non-const reference is a reference to a variable of type non-const.
Const references can be initialized to different types of objects or right values (such as literal constants), but not non-const references.
In the case of binding to different types of ref2, the compiler converts the code associated with ref2 as follows:
Ref2 is actually bound to a temporary variable, and if ref2 is not const, then it is reasonable to change the value of d by modifying ref2, but d does not change. So to avoid this problem, ref2 can only be const.
A non-const reference can only be bound to an object of the same type as the reference, whereas a const reference can be bound to an object of a different but related type or to an rvalue.
const int i = 10;
const int &ref = i;
Ref can be read, but not modified. This makes sense, because I itself cannot be modified, and of course cannot be modified by ref. So it is illegal to assign a const variable to a non-const reference.
int &ref1 = i; // error: nonconst reference to a const object
A non-const reference is a reference to a variable of type non-const.
Const references can be initialized to different types of objects or right values (such as literal constants), but not non-const references.
// 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;
In the case of binding to different types of ref2, the compiler converts the code associated with ref2 as follows:
int temp = d;
const int &ref2 = temp; // bind ref2 to temporary
Ref2 is actually bound to a temporary variable, and if ref2 is not const, then it is reasonable to change the value of d by modifying ref2, but d does not change. So to avoid this problem, ref2 can only be const.
A non-const reference can only be bound to an object of the same type as the reference, whereas a const reference can be bound to an object of a different but related type or to an rvalue.