2011-12-22 14 views
17

當然,這不會編譯:文字數字是否可變?

int &z = 3; // error: invalid initialization of non-const reference .... 

,這將編譯:

const int &z = 3; // OK 

現在考慮:

const int y = 3; 
int && yrr = y; // const error (as you would expect) 
int && yrr = move(y); // const error (as you would expect) 

這些下一行做編譯我。我認爲它不應該。

int && w = 3; 
int && yrr = move(3); 
void bar(int && x) {x = 10;} 
bar(3); 

那最後兩行是不是允許文字3被修改? 3和const int有什麼區別?最後,「修改」文字有沒有危險?

(克++ - 4.6(GCC)4.6.2 -std=gnu++0x -Wall -Wextra

+1

回答我自己的問題:在'move(3)'也許3先被複制來創建一個臨時int將在語句結束時被銷燬。這是解釋嗎? – 2011-12-22 01:37:50

+0

在你的第二條語句中:const &z = 3;你缺少類型說明符。所以它不會編譯。 – 2011-12-22 01:38:24

+0

謝謝@CJohnson,我通常在這裏複製並粘貼工作代碼。但是我對那一班班輪粗心大意! – 2011-12-22 01:39:24

回答

13

的右值參考字面3

int && w = 3; 

實際上被綁定到一個臨時性的計算表達式的結果3。它不綁定到一些柏拉圖式的字面3.

(以下所有標準引用是從2011年3月草案,n3242)

3.10/1 「左值和右值」

The value of a literal such as 12, 7.3e5, or true is also a prvalue

然後8.5。 3「參考」給出勢必參考如何下降到最後的情況下,它說的規則:

Otherwise, a temporary of type 「cv1 T1」 is created and initialized from the initializer expression using the rules for a non-reference copy-initialization (8.5). The reference is then bound to the temporary.

,並給出作爲一個例子,一些很接近什麼在你的問題:

double&& rrd = 2; // rrd refers to temporary with value 2.0 
+0

謝謝,但如果這是真的,那麼不應該這樣工作? 'move(3)= 6;'相反,我得到一個錯誤「*錯誤:使用xvalue(右值引用)作爲左值*」。現在是時候瞭解xvalues和prvalues以及所有這些:-) – 2011-12-22 01:57:06

+3

感謝您的回答,我想我可以在幾秒鐘前回復我的評論。我可以看到'move(3)'是一個右值(顯然,它是未命名的)。而在我的函數'void bar(int && x){x = 10;}'裏面有'x'的名字。這似乎是'x = 6'和'move(3)= 6'之間的區別。兩者都是&&,但一個是左值,另一個不是。這個區別是導致錯誤信息'move(3)= 6'。 – 2011-12-22 02:06:59

+0

@Aaron:(你遲到了)除了你的評論:在某處,標準規定了一個有名的右值是一個左值,所以是的,這正是它的工作原理。 :) – Xeo 2012-01-11 04:20:06

相關問題