在函数 return 值中定义新类型
Define a new type in a function return value
我惊讶地发现以下代码在 MSVC 下编译、运行并产生了预期的输出:
#include <iostream>
using namespace std;
struct Foo{
int _x;
Foo(int x): _x(x) {}
} //Note: no semi-colon after class definition.
//Makes this behave as a return type for the following function:
Foo_factory(int x)
{return Foo(x);}
int main (int argc, char* argv[])
{
Foo foo = Foo_factory(42);
cout << foo._x << endl; //Prints "42"
return 0;
}
看到 MinGW 编译失败并出现错误 "new types may not be defined in a return type",我并不感到意外。这只是标准的另一个 Microsoft 例外,还是合法的 C++?
在 N3797 (C++14) 和 N3485 (C++11) 中,§8.3.5 [dcl.fct]/9 明确开始于:
Types shall not be defined in return or parameter types.
因此,您的代码无效,GCC 诊断正确。
我惊讶地发现以下代码在 MSVC 下编译、运行并产生了预期的输出:
#include <iostream>
using namespace std;
struct Foo{
int _x;
Foo(int x): _x(x) {}
} //Note: no semi-colon after class definition.
//Makes this behave as a return type for the following function:
Foo_factory(int x)
{return Foo(x);}
int main (int argc, char* argv[])
{
Foo foo = Foo_factory(42);
cout << foo._x << endl; //Prints "42"
return 0;
}
看到 MinGW 编译失败并出现错误 "new types may not be defined in a return type",我并不感到意外。这只是标准的另一个 Microsoft 例外,还是合法的 C++?
在 N3797 (C++14) 和 N3485 (C++11) 中,§8.3.5 [dcl.fct]/9 明确开始于:
Types shall not be defined in return or parameter types.
因此,您的代码无效,GCC 诊断正确。