Skip to content

detect performance-unnecessary-value-param when used methods have const versions #59750

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
firewave opened this issue Dec 30, 2022 · 4 comments

Comments

@firewave
Copy link

#include <algorithm>
#include <vector>

bool f1_a(std::vector<int>v)
{
    return v.size() == 1 && v.front() == 1;
}

bool f1_b(std::vector<int>v)
{
    return v.size() == 1 && *v.begin() == 1;
}

bool f1_c(std::vector<int>v) // warning
{
    return v.size() == 1 && *v.cbegin() == 1;
}

bool f2_a(std::vector<int>v)
{
    return std::any_of(v.begin(), v.end(), [](int i) {
        return i == 1;
    });
}

bool f2_b(std::vector<int>v) // warning
{
    return std::any_of(v.cbegin(), v.cend(), [](int i) {
        return i == 1;
    });
}

https://godbolt.org/z/8v9vhdcdq

In all the cases above the given container is never modified so it is possible to change it to a const reference instead.

In case of begin()/end() the code can be const-ified so the warning will be able to catch it. In case of a method like front() or back() there's is no version that explicitly returns a constant value (like cfront() or cback()). To trigger this warning the code could awkwardly be changed to use *cbegin() or *std::prev(cback()) instead.

It would be great if it could be detected that no refence to the vector is being used and the warning is triggered.

I assume there's possibly cases for other methods and containers.

@llvmbot
Copy link
Member

llvmbot commented Dec 30, 2022

@llvm/issue-subscribers-clang-tidy

@firewave firewave changed the title detect performance-unnecessary-value-param when used methodd have const versions detect performance-unnecessary-value-param when used methods have const versions Dec 30, 2022
@firewave
Copy link
Author

This information could probably be leveraged for the misc-const-correctness check as well.

@firewave
Copy link
Author

Related/duplicate: #69577.

@firewave
Copy link
Author

This information could probably be leveraged for the misc-const-correctness check as well.

See #58246.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants