在函数返回值中定义新类型

时间:2015-04-13 15:21:53

标签: c++ visual-c++

我很惊讶地发现以下代码在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无法使用错误进行编译&#34;新类型可能未在返回类型中定义&#34;。这只是该标准的另一个Microsoft例外,还是这个合法的C ++?

1 个答案:

答案 0 :(得分:6)

在N3797(C ++ 14)和N3485(C ++ 11)中,§8.3.5[dcl.fct] / 9明确地以:

开头
  

不应在返回或参数类型中定义类型。

因此,您的代码无效,GCC对其进行诊断是正确的。

相关问题