Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most vexing parse C++11

Tags:

c++

c++11

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();
}
like image 238
test program Avatar asked Jun 12 '26 05:06

test program


1 Answers

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.

like image 108
Mike Seymour Avatar answered Jun 18 '26 01:06

Mike Seymour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!