2013-05-05 39 views
15

我就遇到了這個,而在gcc編譯一些移植的代碼。基本上,這奇怪的代碼編譯在Visual Studio這真的只是吹拂我的心靈:綁定到臨時的Visual Studio錯誤的非const引用?

class Zebra {int x;}; 
Zebra goo() {Zebra z; return z;} 
void foo(Zebra &x) 
{ 
    Zebra y; 
    x = y; 
    foo(goo()); 
} 

Visual studio讓這一個蒼蠅。 gcc會將其視爲編譯錯誤。有趣的是,如果您將int定義爲Zebra,則VC++將會投訴。相當矛盾的行爲。思考?

+11

這是不是一個錯誤,這是一個編譯器擴展,而且是一個邪惡的一個。 – chris 2013-05-05 02:59:54

+1

MSVC確實有'警告C4239:非標準擴展used',但顯然你有警告關閉。 – MSalters 2013-05-06 09:21:14

+2

我不明白你爲什麼需要使用無限遞歸函數來演示這個。 – Neutrino 2016-11-24 16:19:26

回答

18

這是老擴展到Visual Studio中,我能找到微軟網站上只提到了這個錯誤報告:Temporary Objects Can be Bound to Non-Const References,其中有下面的示例代碼:

struct A {}; 

A  f1(); 
void f2(A&); 

int main() 
{ 
    f2(f1()); // This line SHALL trigger an error, but it can be compiled without any  errors or warnings. 
} 

之一答覆筆記:

There is a level 4 warning (level 4 warning are enabled if you pass /W4 to the compiler) for it

本博客文章:Visual C++ is so Liberal覆蓋該擴展指出:

Using Disable Language Extensions (/Za) makes it an error:

2

正如有人說,這是由於微軟C++的擴展。雖然/Za標誌不推薦,因爲它可以打破的東西。

而是使用/permissive-開關更好的標準符合性,你會得到這些情況下健康的錯誤。請注意,這個標誌是可用的,因爲2017年VS

The switch /Za does not support certain key Microsoft SDK header files. By contrast /permissive- offers a useful conformance mode where input C++ code is interpreted according to ISO C++ rules but also allows conforming extensions necessary to compile C++ on targets supported by Visual C++.

更多信息是Visual C++ Team Blog

+0

這也許值得指出的是,'/ permissive'標誌可自2017年VS您可以通過包含從文章的相關報價提高這個答案。就像現在這樣,爲什麼要介紹它和它與'/ Za'的關係 – bolov 2017-10-23 08:59:10

相關問題