为什么 clang 不警告模板中的死代码?

Why doesn't clang warn of dead code in templates?

本文关键字:代码 clang 警告 为什么      更新时间:2023-10-16

使用-Weverything编译时,clang为什么不在下面的模板中标记死代码,而是在函数中标记它?请注意,在这两种情况下,它都会标记未使用的变量警告。

#include <iostream>
template <class Item> class ItemBase {
  public:
    bool performWork() {
        int i;
        std::cout << "foo" << std::endl;
        return true;
        std::cout << "dead code in template" << std::endl;
    }
};
bool badFunc();
bool badFunc() {
    int i;
    std::cout << "foo" << std::endl;
    return true;
    std::cout << "dead code in function" << std::endl;
}
int main() {
    ItemBase<float> tester;
    tester.performWork();
    badFunc();
}

叮当声输出:

test.cpp:24:13: warning: unused variable 'i' [-Wunused-variable]
        int i;
            ^
test.cpp:33:9: warning: unused variable 'i' [-Wunused-variable]
    int i;
        ^
test.cpp:36:42: warning: code will never be executed [-Wunreachable-code]
    std::cout << "dead code in function" << std::endl;
                                         ^~
3 warnings generated.

我看不出有任何原因导致没有发出警告(除了clang中的错误)。

我猜clang对模板中的警告过于谨慎,因为它无法判断模板的任何实例化都不会执行代码(尽管这对人类来说是显而易见的),所以它只是不发出警告。但这只是一个假设。