Is no parentheses on a constructor with no arguments a language standard?

落爺英雄遲暮 提交于 2019-11-26 12:20:37
CB Bailey

Although MyClass myObj(); could be parsed as an object definition with an empty initializer or a function declaration the language standard specifies that the ambiguity is always resolved in favour of the function declaration. An empty parentheses initializer is allowed in other contexts e.g. in a new expression or constructing a value-initialized temporary.

This is called the most vexing parse issue. When the parser sees

MyClass myObj();

It thinks you are declaring a function called myObj that has no parameters and returns a MyClass.

To get around it, use:

MyClass myObj;

I found this in the C++ standard (§8.5.8):

An object whose initializer is an empty set of parentheses, i.e., (), shall be value-initialized.

[Note: since () is not permitted by the syntax for initializer,

X a ();

is not the declaration of an object of class X, but the declaration of a function taking no argument and returning an X. The form () is permitted in certain other initialization contexts (5.3.4, 5.2.3, 12.6.2). —end note ]

This is a fairly well known issue, and isn't compiler dependent. Essentially, what you were doing was declaring a function returning type MyObj. Not surprisingly, you couldn't call its constructor. See the C++ faq lite for a good explanation

AProgrammer

Yet another most-vexing-parse hit. See for instance Sort function does not work with function object created on stack?

MyClass myObj();

That's parsed as a function declaration, the function is called myObj, takes no arguments and returns MyClass object. I've never seen a compiler accepting that. On the other hand MyClass* myPtr = new MyClass(); is acceptable, may be that got you confused?

Your line makes the compiler think you are declaring a function named myObj which takes no arguments and returns a MyClass. This ambiguity resolution is indeed annoying.

The standard does not require parentheses.

int* x = new int;

is legal syntax.

In your case myclass myobj(); is a function prototype. Whereas myclass myobj; is a variable.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!