llvm / llvm-project

The LLVM Project is a collection of modular and reusable compiler and toolchain technologies.
http://llvm.org
Other
28.26k stars 11.67k forks source link

[clang-tidy] false positive report of possible memory leak when capturing std::function in lambda multiple times #108823

Open valarx opened 2 weeks ago

valarx commented 2 weeks ago

Minimal reproduction example:

#include <functional>

std::function<void()> combine(const std::function<void()>& lhs, const std::function<void()>& rhs)
{
    auto thisTemporaryCausesWarning = [lhs, rhs] (){};
    return { std::move(thisTemporaryCausesWarning) };

int main()
{
    std::function<void()> f;
    f = combine(f, nullptr);
    f = combine(f, nullptr); // this call triggers warning
}

As described, when calling combine two times in this scenario, if the temporary variable is present in combine implementation, then clang-tidy triggers warning "potential memory leak" which points to implementation of constructor of std::function. If the temporary variable is not present (so, the resulting lambda is passed into std::function directly), then the warning is not triggered.

Clang-tidy version is 18.1

EugeneZelenko commented 2 weeks ago

Could you please try 19 or main branch? https://godbolt.org should be helpful.

chrchr-github commented 2 weeks ago

https://godbolt.org/z/5T9KPc4bj

llvmbot commented 2 weeks ago

@llvm/issue-subscribers-clang-static-analyzer

Author: Anatolii Baranov (valarx)

Minimal reproduction example: ``` #include <functional> std::function<void()> combine(const std::function<void()>& lhs, const std::function<void()>& rhs) { auto thisTemporaryCausesWarning = [lhs, rhs] (){}; return { std::move(thisTemporaryCausesWarning) }; int main() { std::function<void()> f; f = combine(f, nullptr); f = combine(f, nullptr); // this call triggers warning } ``` As described, when calling `combine` two times in this scenario, if the temporary variable is present in `combine` implementation, then clang-tidy triggers warning "potential memory leak" which points to implementation of constructor of `std::function`. If the temporary variable is not present (so, the resulting lambda is passed into std::function directly), then the warning is not triggered. Clang-tidy version is 18.1