简体   繁体   中英

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.

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.

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.

Difference :

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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