本文介紹了一個 VS2010 錯誤?允許在沒有警告的情況下綁定非常量引用到右值?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
限時送ChatGPT賬號..
string foo() { return "hello"; }
int main()
{
//below should be illegal for binding a non-const (lvalue) reference to a rvalue
string& tem = foo();
//below should be the correct one as only const reference can be bind to rvalue(most important const)
const string& constTem = foo();
}
- GCC 是給出編譯錯誤的好方法:從
類型的臨時對象對
std::string&
類型的非常量引用無效初始化std::string - VS2008 還不錯,至少它給出了一個編譯警告:警告 C4239:使用了非標準擴展:正在初始化":從
std::string
到std::string &
的轉換 非常量引用只能綁定到左值 - 問題來了 - VS2010(SP1) 沒有任何問題錯誤或警告,為什么??!!我知道 VS2010 中的 rvalue reference 可用于綁定 rvalue 但我沒有使用
&&
,而是在演示代碼中,我只是使用非常量左值引用!
- GCC is the good one to give a compile error: invalid initialization of non-const reference of type
std::string&
from a temporary of typestd::string
- VS2008 is not too bad as at least it gives a compile warning:
warning C4239: nonstandard extension used : 'initializing' :
conversion from
std::string
tostd::string &
A non-const reference may only be bound to an lvalue - Here comes the problematic one - VS2010(SP1) comples fine WITHOUT any
error or warning, WHY ??!!
I know rvalue reference in VS2010 can be used to bind with rvalue but I am NOT using
&&
, instead in the demo code, I was just using non-const lvalue reference !
這里有人能幫我解釋一下VS2010的行為嗎?是bug嗎!?謝謝
Can somone help me explain the behavior of VS2010 here? Is it a bug !? Thanks
推薦答案
這是 VS 編譯器的已知問題/功能.他們一直允許這樣做,并且似乎沒有任何推動刪除該擴展.
That is a known issue/feature of the VS compilers. They have always allowed that and there does not seem to be any push into removing that extension.
這篇關于一個 VS2010 錯誤?允許在沒有警告的情況下綁定非常量引用到右值?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!