False positive on explicit return value from lambda cpp:S3574

Environment: SonarLint, 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

Thank you for the report. Indeed in this situation there is no good way to silence the issue, as adding return type to the lambda, will (correctly) trigger message regarding unreachable return.

[](int) -> bool { 
  return true;

I have a created an ticket for that issue CPP-3282.

We are also considering replacing this rule in the SonarWay profile with less strict alternative (see CPP-3135).

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.