Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a new type in a function return value

Tags:

c++

visual-c++

I was surprised to discover that the following code compiles, runs, AND produces the expected output under 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;
}

I was less surprised to see MinGW fail to compile with the error "new types may not be defined in a return type". Is this just another Microsoft exception to the standard, or is this legal C++?

like image 976
Carlton Avatar asked Mar 17 '23 10:03

Carlton


1 Answers

In N3797 (C++14) and N3485 (C++11), §8.3.5 [dcl.fct]/9 explicitly starts with:

Types shall not be defined in return or parameter types.

Thus, your code is invalid and GCC is correct to diagnose it.

like image 103
chris Avatar answered Mar 23 '23 07:03

chris