Is there a way to force the “most vexing parse” to be an error, even on a class by class basis?

℡╲_俬逩灬. 提交于 2019-12-05 16:55:13

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());

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