2016-09-22 88 views
6

我對這兩者感到困惑。我知道C++的引用本質上是不變的,一旦設置,它們就不能被改變來引用別的東西。「const int&jj」和「int&const jj」有什麼區別?

+3

請問你的編譯器接受第二個變種? – juanchopanza

+1

請指定哪個編譯器接受第二個變體。 – Angew

+3

@HumamHelfawi這根本不是重複的。這個問題涉及'const int&'和'int const&',它們都是有效的(和等價的)形式。這個處理'const int&'和語法錯誤'int&const'。 – Angew

回答

9

const int&表示參考常量int。 (類似地,int&意味着參照非const int。)

int& const字面意思const引用(到非const int),這是在C++中無效,因爲參考本身不能是常量限定。

$8.3.2/1 References [dcl.ref]是形成不良的,當cv修飾符 通過使用一個typedef名的介紹除了

CV-合格的引用([dcl.typedef], [temp.param])或decltype-specifier([dcl.type.simple]),在這種情況下,cv-qualifiers將被忽略。

正如你所說,引用本質上是恆定的,一旦設置,它們就不能被改變來引用別的東西。 (我們不能在初始化後重新引用引用。)這意味着引用總是「const」,那麼const限定的引用或者const-unqualified引用實際上可能沒有意義。

3

const將限定符應用於引用意味着您無法更改引用的值。例如:

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是一個編譯錯誤。

3

差異:

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

int& const jj // ill formed code that should trigger a compiler error 
相關問題