GCC's two unusual error messages

六月ゝ 毕业季﹏ 提交于 2019-12-05 23:18:51

The key to understanding what is happening is to realize that: adder(item); is a definition of a local variable named item and having type adder; the parentheses are superfluous, but perfectly permissable. If you want to call the constructor, you'll have to disambiguate, by writing it in some way that cannot be interpreted as a data definition, say: adder((item)); (I'm not sure what use this may be. It constructs a temporary object of adder, then destructs it at the end of the expression.)

The actual error messages should be clear(er) once the statement is understood as a data declaration: function parameters are treated as if they were defined in the top level block of the function, so adder(item) is a duplicate (and contradictory) definition, and adder doesn't have a default constructor, so you can't define an instance of it without providing arguments.

Which indicates that the compiler is looking for default constructor? But I'm wondering why is the compiler looking for it when in fact my code doesn't use it at line 6?

Because compiler think that you declare local variable with name item.

http://codepad.org/YBPKCvmm

I only have access to the C++0x draft at the moment, so I can't give you the current chapter and verse, but I don't think much has changed. In 0x it's in section 6.8 - Ambiguity Resolution:

There is an ambiguity in the grammar involving expression-statements and declarations: An expression-statement with a function-style explicit type conversion (5.2.3) as its leftmost subexpression can be indistinguishable from a declaration where the first declarator starts with a (. In those cases the statement is a declaration.

[...]

T(a); // declaration

That is, a declaration of a variable named "a" of type T.

If your adder<T>(item) were to define a temporary (un-named) object, it would be an expression-statement, but if something can be parsed as either a declaration-statement or an expression-statement, C++ parses it as a declaration-statement.

[...] the resolution is to consider any construct that could possibly be a declaration a declaration. (8.2)

In other words, it's a cousin to everyone's dear old friend, the Most Vexing Parse.

Update: I looked at ambiguity resolution in C++03, and those passages are identical.

"shadowing" means that two objects have the same name, which the language allows at this point, but might not be intended.

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