Environment: SonarLint 5.3.0.36775, Clion 2021.1.3, Ubuntu 20.04.3
False positive on the below code. SonarLint suggests to remove explicit return type specification of lambda, but that code would be ill-formed, as the lambda never returns, it exits with an exception thrown. In such case explicit return type is necessary, and can’t be avoided.
Lambdas which always throws exceptions are useful for example for unit testing robust behaviour of library functions that take callback arguments.
#include <stdexcept>
#include <vector>
#include <algorithm>
#define THROW_EXCEPTION(txt) throw std::runtime_error(txt)
template <typename Predicate>
bool systemUnderTest(const Predicate & predicate)
{
std::vector<int> dummy{3, 4, 5, 6};
return std::any_of(dummy.begin(), dummy.end(), predicate);
}
void unitTest()
{
auto mockFailingPredicate = [](int) -> bool { THROW_EXCEPTION("foo"); }; // false positive on this line
systemUnderTest(mockFailingPredicate);
}