是否有任何编译器选项或工具(无论是 Visual C++、GCC、Clang 或其他的一部分)可以分析我的代码并告诉我在哪里比较函数指针,就像上面的代码一样?
我不确定是否存在这样的编译器选项。
然而,有这样一个工具。整洁。你可以为 clang-tidy 编写自己的检查,如果你遵循的话,实际上非常容易这个博客 http://bbannier.github.io/blog/2015/05/02/Writing-a-basic-clang-static-analysis-check.html。具体来说,AST 已经附带了一堆匹配器,它们应该可以处理您想要的用例。
像这样的东西似乎有效:
binaryOperator(
anyOf(hasOperatorName("=="), hasOperatorName("!=")),
hasLHS(ignoringImpCasts(declRefExpr(hasType(functionType())))),
hasRHS(ignoringImpCasts(declRefExpr(hasType(functionType())))))
这标志着OP中的示例:
fp.cxx:3:25: note: "root" binds here
int main(void) { return test1 == test2; }
^~~~~~~~~~~~~~
这专门适用于 OP 情况,但实际上您必须更明确才能匹配所有其他可能的情况:
const auto AnyFunc = ignoringImpCasts(declRefExpr(hasType(anyOf(
functionType(),
pointsTo(functionType()),
references(functionType())))));
Finder->AddMatcher(binaryOperator(
anyOf(hasOperatorName("=="), hasOperatorName("!=")),
hasLHS(AnyFunc),
hasRHS(AnyFunc)).bind("op"), this);
或者类似效果的东西。