2013-10-31 33 views
3
char f1(); 
void f2(char&); 

struct A {}; 

A f3(); 
void f4(A&); 

int main() 
{ 
    f2(f1()); // error C2664. This is as expected. 
    f4(f3()); // OK! Why??? 
} 

錯誤C2664: '無效F4(炭&)':不能從 '字符' 轉換參數1至爲什麼非const引用參數可以綁定到臨時對象?

我被教導 '字符&',在C++一個非const引用參數不能綁定到臨時對象;並在上面的代碼中,f2(f1());按預期觸發錯誤。

但是,爲什麼相同的規則不適用於代碼行f4(f3());

PS:我的編譯器是VC++ 2013.即使我在註釋行f2(f1());,那麼包含f4(f3());的代碼將被編譯時不會出現任何錯誤或警告。

更新:

MSDN說:

在Visual C++的早期版本中,非const引用可以 綁定到臨時對象。現在,臨時對象只能綁定 以引用const。

所以我認爲這是一個VC++的bug。我已經向VC++ team提交了一個錯誤報告

+0

你嘗試不F2大廈(F1() )在代碼中?它可能會停在第一個錯誤。 – scaryrawr

+0

如果我註釋行'f2(f1());',那麼代碼就OK了。 – xmllmx

+0

MSVC以支持這種編譯器擴展而聞名。不知道大約2013. – yngccc

回答

4

如果用the /Za option編譯禁用語言擴展,編譯器會拒絕兩個電話:

> cl /Za test.cpp 
Microsoft (R) C/C++ Optimizing Compiler Version 18.00.21005.1 for x86 
Copyright (C) Microsoft Corporation. All rights reserved. 

test.cpp 
test.cpp(11): error C2664: 'void f2(char &)' : cannot convert argument 1 from 'char' to 'char &' 
test.cpp(12): error C2664: 'void f4(A &)' : cannot convert argument 1 from 'A' to 'A &' 
     A non-const reference may only be bound to an lvalue 

有幾個(非常受限的)的情況中,編譯器,用語言擴展啓用,仍然允許非常量左值引用綁定到右值表達式。我的理解是,這主要是爲了避免破壞依賴於這個「擴展」的幾個龐大的遺留代碼庫。

(一般情況下,不建議使用/雜誌的原因很多,但主要是因爲Windows的SDK頭不能與/雜誌選項進行#included)

2

您的編譯器不符合標準(可能這是編譯器擴展的文檔?)。 GCC提供了以下錯誤:

main.cpp: In function 'int main()': 
main.cpp:11:11: error: invalid initialization of non-const reference of type 'char&' from an rvalue of type 'char' 
    f2(f1()); // error C2664. This is as expected. 
     ^
main.cpp:2:6: error: in passing argument 1 of 'void f2(char&)' 
void f2(char&); 
    ^
main.cpp:12:12: error: invalid initialization of non-const reference of type 'A&' from an rvalue of type 'A' 
    f4(f3()); // OK! Why??? 
      ^
main.cpp:7:6: error: in passing argument 1 of 'void f4(A&)' 
void f4(A&); 
相關問題