问题
Is it possible (with any modification of class A) to have the following work? i.e., make the most vexing parse an error?
class A {
};
int main() {
A a(); // can this be forced to be an error??
A b; // this should work
}
回答1:
No modification of the class A
will have any effect on how a declaration A a();
is parsed. The parser determines that this is a function declaration before it even bothers to look at the definition of A
. In fact the definition of A
doesn't even need to be visible to parse this statement; A forward declaration is sufficient.
However compilers generally have a warning for this and you can probably turn that into an error. For example with clang you can use the flag -Werror=vexing-parse.
struct A;
A a(); // no error
int main() {
A a(); // error
}
clang++ -std=c++11 -Weverything -Werror=vexing-parse main.cpp
main.cpp:6:8: error: empty parentheses interpreted as a function declaration [-Werror,-Wvexing-parse]
A a();
^~
main.cpp:6:8: note: replace parentheses with an initializer to declare a variable
A a();
^~
{}
1 error generated.
Although technically speaking A a();
isn't the syntax known as the most vexing parse. That would be:
A a(B());
回答2:
There is no way in the current language specification which could make this code an error. Normally, you just get a funny error message when you try to use the "object". However, some compilers do warn about the situation (e.g. clang):
clang++ -W -Wall -Werror -c -o vexing.o vexing.cpp
vexing.cpp:5:8: error: empty parentheses interpreted as a function declaration [-Werror,-Wvexing-parse]
A a(); // can this be forced to be an error??
^~
来源:https://stackoverflow.com/questions/19009306/is-there-a-way-to-force-the-most-vexing-parse-to-be-an-error-even-on-a-class