问题
I am confused with the two. I am aware of the C++ references which are inherently constant and once set they cannot be changed to refer to something else.
回答1:
const int&
means reference to const int
. (Similarly, int&
means reference to non-const int
.)
int& const
literally means const reference (to non-const int
), which is invalid in C++, because reference itself can't be const-qualified.
$8.3.2/1 References [dcl.ref]
Cv-qualified references are ill-formed except when the cv-qualifiers are introduced through the use of a typedef-name ([dcl.typedef], [temp.param]) or decltype-specifier ([dcl.type.simple]), in which case the cv-qualifiers are ignored.
As you said, references are inherently constant and once set they cannot be changed to refer to something else. (We can't rebind a reference after its initialization.) This implies reference is always "const", then const-qualified reference or const-unqualified reference might not make sense actually.
回答2:
const
qualifier applied to reference means that you can't change the referenced value. For example:
void foo(int& arg) {
arg = 1; // OK. The value passed by a caller will be changed in-place.
}
void foo(const int& arg) {
arg = 1; // Compilation error.
}
int& const jj
is a compilation error.
回答3:
Difference :
const int& jj// means a reference to const int.
int& const jj // ill formed code that should trigger a compiler error
来源:https://stackoverflow.com/questions/39631317/what-is-the-difference-between-const-int-jj-and-int-const-jj