Consider the following code:
struct Foo
{
};
struct Bar
{
explicit Bar(const Foo&)
{
}
};
int main()
{
Foo foo;
Bar bar(foo); // Okay.
Bar(foo); // Will not compile.
(Bar(foo)); // Okay. Unnamed temporary requires parenthesis.
}
Why are the parenthesis around the temporary version required? What ambiguity do they solve?
My hunch is: I think the compiler sees Bar(foo) as a declaration for a function, but I’m not sure why that would be the case since foo (the instance) is not a type. The parenthesis, therefore, force the above to be treated as an expression, not as a forward declaration.
Congratulations on discovering the most vexing parse.
Scott Meyers describes it as follows:
In your case, introducing parentheses disambiguates the parse, forcing it to become a local.