Menu

False positive CppCheck(selfAssignment) in closure capture list when capturing tuple decomposed alias.

Lonchik
2021-03-31
2021-04-03
  • Lonchik

    Lonchik - 2021-03-31

    I'm running cppcheck via an extension to VSCode (I have 3 or 4 C++ related extensions, and not sure part of which cppcheck is run), and noticed a false positive selfAssignment being flagged for cases where such assignment is required by compiler/spec.

    Consider the following code:

    auto [partA, partB] = getSomeTupleOfSomething(); // returns std::tuple<A,B>.
    
    auto someLambda = [partB = partB]() { doSomething(partB)};
    

    cppcheck flags selfAssignment on the lambda definition capture list because it sees partB = partB.

    However, at least in C++17 - I believe specification may've changed for C++20 - tuple decomposition doesn't create variables, but rather aliases (perhaps called something different in the spec), which can be used like variables in most, but not all scenarios. Capture list is one such place, and defining capture list as simply [partB](){...} results in the following error (clang):

    error: 'partB' in capture list does not name a variable
    note: 'sideB' declared here
    

    Changing capture list to [partB = partB] creates a true partB variable (left side of assignment) from alias partB (right side of assignment), which can now be captured into lambda's closure.

    CppCheck flagging selfAssignment due to seeing partB = partB is, therefore, a false positive.

     
  • Daniel Marjamäki

     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.