-
Notifications
You must be signed in to change notification settings - Fork 15.3k
Open
Labels
Description
#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.
Skylion007