0

I wouldn't be surprised if this has been discussed before, but I've no idea what the magic search terms are to find the answer.

Why does this compile,

int main() {
  int* p(new int());
  return 0;
}

while this doesn't,

class X {
  int* p(new int());
};

yet this does?

class X {
  int* p = new int();
};
Apollys supports Monica
  • 2,938
  • 1
  • 23
  • 33

2 Answers2

1

This is a most vexing parse.

In the second case, I believe p is being parsed as a function (but I'm not sure). Regardless, it's not being parsed as a pointer to an int initialized with the value new int(). Replacing the parentheses with curly braces fixes the issue.

Although I have found the source of the issue, I would be grateful if someone could tell me how exactly the parser is interpreting the second example in the question. I still don't fully understand what is happening.

Apollys supports Monica
  • 2,938
  • 1
  • 23
  • 33
  • I don't think "most vexing parse" applies here. The same tokens `int *p(new int());` are fine inside a function block and declare a pointer object, not a function, since there's no way `new int()` could be a parameter list. – aschepler Jan 24 '19 at 01:05
  • That's why I was so confused. I may definitely be wrong to call it a most vexing parse, but it is a very vexing parse nevertheless. – Apollys supports Monica Jan 24 '19 at 01:12
1

The "in-class" initialization that you are trying to use is a C++11 feature that requires either = or {} initializer syntax

class X {
  int* p = new int();
};

or

class X {
  int* p{ new int() };
};

Firstly, C++11 places extra emphasis of the uniform initialization syntax, based around {} initializers. Secondly, () syntax in this context would potentially create unnecessary ambiguities with class member function declaration syntax.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
  • I do wonder if a paper behind the language addition mentions if the reason for not allowing parentheses-style initializers was specifically to avoid an analogue of the Most Vexing Parse. – aschepler Jan 24 '19 at 01:09
  • My problem with uniform initialization syntax is that I'm constantly using vectors which interpret curly braces differently... – Apollys supports Monica Jan 24 '19 at 01:13
  • 1
    @aschepler: Answer here - https://stackoverflow.com/a/24837330/187690 - says that this is related to ambiguous parsing, but it is more of a *lookup* ambiguity, not a pure Most Vexing Parse ambiguity. – AnT stands with Russia Jan 24 '19 at 01:18