Menu ▾ ▴

constParameterReference false positive

CJ Wood
2026-10-04
2026-10-05
  • CJ Wood

    CJ Wood - 2026-10-04

    I see a false positive running cppcheck 2.22.0 against the following code.

    Note the parameter cannot be declared as reference to const because its job is to match both const and mutable references, and return a reference to a member which retains the const-ness of the first argument (similar to the 'deduce this' pattern). The static asserts demonstrate the intended use cases.

    Note also that the false positive goes away if the concept is inlined as a template requires clause on the function itself (first argument becomes T&).

    #include <concepts>
    #include <type_traits>
    
    // Reproduce with:
    // cppcheck --enable=all --inconclusive --check-level=exhaustive constParameterReference.cpp
    enum class player
    {
        black,
        white
    };
    
    struct captures
    {
        unsigned int captured_by_black{0};
        unsigned int captured_by_white{0};
    };
    
    template <typename T>
    concept captures_type = std::same_as<std::remove_cvref_t<T>, captures>;
    
    constexpr auto& captured_pieces_for(captures_type auto& captures, player current_player)
    {
        return current_player == player::black
            ? captures.captured_by_black
            : captures.captured_by_white;
    }
    
    /// static assertions show intended behaviour for captured_pieces_for with different cv-qualifiers.
    static_assert(std::same_as<decltype(captured_pieces_for(std::declval<captures&>(), player::black)), unsigned int&>);
    static_assert(std::same_as<decltype(captured_pieces_for(std::declval<const captures&>(), player::black)), const unsigned int&>);
    
    int main()
    {
        captures captures{};
        auto& total = captured_pieces_for(captures, player::black);
        ++total;
        return captures.captured_by_black == 1 ? 0 : 1;
    }
    

    The error output:

    constParameterReference.cpp:21:57: style: Parameter 'captures' can be declared as reference to const [constParameterReference]
    constexpr auto& captured_pieces_for(captures_type auto& captures, player current_player)
                                                            ^
    
     
  • CHR

    CHR - 2026-10-05

    Thanks for reporting, ticket is here: https://trac.cppcheck.net/ticket/15087

     

Log in to post a comment.