Function definition or variable definition?

Why does the compiler interpret this line as a function definition, and not as a variable definition:

Y y(X()); 

in the following code:

 #include <iostream> struct X { X() { std::cout << "X"; } }; struct Y { Y(const X &x) { std::cout << "Y"; } void f() { std::cout << "f"; } }; int main() { Y y(X()); yf(); } 

VS2010 gives the following error in the line "yf ();"

 left of '.f' must have class/struct/union 

What part of the standard describes this behavior? The answer to the following question does not contain details: The most unpleasant parsing

+5
source share
2 answers

Consider this:

float foo( int () )

This declares a function foo (accepts a function that returns an int ) that returns a float .

Now read

 Y y(X()); 

as y as a function (receiving a function returning X ) returning y

The problem arises due to C ++ most unpleasant analysis

Can be solved with

  Y y{ X() }; // requires C++11 

or

 Y y( ( X() ) ); // ^ ^ notice parenthesis 

Update based on edit:

Quote from the standard:

Β§ 8.2 Resolution of ambiguity [dcl.ambig.res]

1 - Uncertainty arising from the similarity between a function-style cast and a declaration referred to in 6.8 may also arise in the context of a declaration. In this context, the choice is between declaring a function with an excessive set of parentheses around the parameter name and declaring an object using a style function as an initializer. In the same way as for the ambiguities mentioned in 6.8 , permission should consider any construction that may be a declaration of declaration. [Note: declarations can be explicitly eliminated using an inefficient style using a = to indicate initialization or removal of redundant parentheses around the parameter name. ]

 [Example: struct S { S(int); }; void foo(double a) { S w(int(a)); // function declaration S x(int()); // function declaration S y((int)a); // object declaration S z = int(a); // object declaration } β€”end example] 

Similar to other examples following this.

+6
source

The most annoying parsing issue . Y y(X()) is actually a function declaration with the name y that returns y and receives an argument to a function of the type that returns X and receives nothing.

He decided in C ++ 11 using {} for the construct object.

+4
source

Source: https://habr.com/ru/post/1204805/


All Articles