I'm confused about Y y {X{}}; what exactly this line does and what is its connection to the most vexing parse. A brief explanation is appreciated:
#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{} };
y.f();
}
what exactly this line does
It creates a temporary X, value-initialising it by calling the default constructor, and then uses that to initialise a Y variable, calling the const X& conversion constructor.
where is connection to Most vexing parse
If you were to try to write this using old-school initialisation syntax
Y y (X());
then the so-called "most vexing parse" would interpret this as a function, rather than a variable, declaration: a function called y, with return type Y and a single parameter, whose type is a (pointer to a) function returning X.
You could add extra parentheses, so that it can't be interpreted as a function declaration:
Y y ((X()));
or, since C++11, you can use brace-initialisation as your example does.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With