Most vexing parse C++11

后端 未结 2 1302
刺人心
刺人心 2020-12-22 02:20

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:



        
相关标签:
2条回答
  • 2020-12-22 02:46

    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.

    0 讨论(0)
  • 2020-12-22 02:53
    Y y {X{}};
    

    This is perfect and creates an object y passing a temporary object of type X to the constructor. There is NO vexing parse (most or otherwise). In fact, the construction using {} was introduced to solve the issue of vexing parse in many cases, such as these:

     Y y1();
     Y y2(X());
    

    Both belongs to (most) vexing parse because of which both declares functions, instead of objects.

    However, if you use curly braces called brace-initialization:

     Y y1{};
     Y y2{X{}}; //as you've done yourself
    

    then both declares objects, not functions, as expected.

    0 讨论(0)
提交回复
热议问题