为什么clang-tidy的deadcode.DeadStores会在使用reference_wrapper的RAII情况下发出警告?

时间:2018-04-30 17:26:06

标签: c++ clang clang-tidy

代码段:

#include <functional>
#include <iostream>

class OnExit
{
public:
    explicit OnExit(const std::function<void()>& f):f_(f){}
    ~OnExit(){f_();}
private:
    std::function<void()> f_;
};

void finish(const bool& details)
{
    std::cout << "foo finished with " << std::boolalpha << details << std::endl;
}

int foo(int i)
{
    bool details = false;
    OnExit action{std::bind(&finish, std::cref(details))};
    if (i < 0)
    {
        throw 0;
    }

    if (i < 10)
    {
        return i;
    }
    int result = i*6;

    details = true;

    if (i < 100)
    {
        return result + 5;
    }

    details = false;
    return result*result;
}

int main()
{
    std::cout << foo(5) << std::endl;
    std::cout << foo(20) << std::endl;
    try
    {
        std::cout << foo(-1) << std::endl;
    }
    catch (...)
    {
        std::cout << "exception" << std::endl;
    }
    std::cout << foo(120) << std::endl;
}

因此,每当程序离开foo()范围时,都会调用函数finish()。变量&#39;细节的价值&#39;阅读并打印。

但......铿锵有力的输出:

2 warnings generated.
<<path>>/neverused.cpp:33:5: warning: Value stored to 'details' is never read [clang-analyzer-deadcode.DeadStores]
details = true;
^
<<path>>/neverused.cpp:33:5: note: Value stored to 'details' is never read
details = true;
^
<<path>>/neverused.cpp:40:5: warning: Value stored to 'details' is never read [clang-analyzer-deadcode.DeadStores]
details = false;
^
<<path>>/neverused.cpp:40:5: note: Value stored to 'details' is never read
details = false;
^

将std :: bind更改为lambda后,没有警告。 我的问题是:bind和/或reference_wrapper背后的魔力是什么以及为什么clang-tidy不理解它?

0 个答案:

没有答案