简体   繁体   English

“const int&jj”和“int&const jj”有什么区别?

[英]What is the difference between “const int& jj” and “int& const jj”?

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. 我知道C ++引用本身就是常量,一旦设置它们就无法更改为引用别的东西。

const int& means reference to const int . const int&表示对const int引用。 (Similarly, int& means reference to non-const int .) (类似地, int&表示对非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. int& const字面意思是const引用(对于非const int ),这在C ++中是无效的,因为引用本身不能是const限定的。

$8.3.2/1 References [dcl.ref] $ 8.3.2 / 1参考文献[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. 除非通过使用typedef-name([dcl.typedef],[temp.param])或decltype-specifier([dcl.type.simple])引入cv-qualifiers,否则Cv限定的引用是不正确的。 ,在这种情况下,cv限定符被忽略。

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. (我们不能在初始化后重新引用引用。)这意味着引用始终是“const”,然后const限定引用或const不合格引用实际上可能没有意义。

const qualifier applied to reference means that you can't change the referenced value. 应用于引用的const限定符意味着您无法更改引用的值。 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. int& const jj是编译错误。

Difference : 区别 :

const int& jj// means a reference to const int.

int& const jj // ill formed code that should trigger a compiler error

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM