I do not understand why this compiles

I'm certainly missing something, but I do not understand why this compiles (with both g++ & clang++):

struct A
{
};
struct B
{
};


int main()
{
A a(B);
}

First of all, B is a type... not a value. How should I interpret this code?

7174 次浏览

It's interpreted as the declaration of a function named a, which takes one argument of type B and returns A.

It's simply a function declaration declaring a to be a function returning A and taking one unnamed parameter of type B.

It is valid because function declarations as opposed to function definitions are allowed within function definitions.

This issue is known as the most vexing parse. The line A a(B); can be interpreted as the declaration of a function named a returning an object of type A and taking an unnamed parameter of type B.

One way to avoid this issue is to use the uniform initialization syntax which was introduced in C++11, which consists in using braces instead of parenthesis: A a{B}; returns an error. The line is now interpreted as a variable declaration initialized with B, which is a type instead of a value.

Here's more information:

The Most Vexing Parse: How to Spot It and Fix It Quickly