no warning on unused lambda with -Wall and -Wextra

Viewed 55

Normally, if you have a lambda and forget to use it, you'll get a warning (if enabled) like any other unused variable.

auto foo = [](){};

would generate warning: unused variable 'foo' or similar.

However, if the lambda captures have side-effects (like bumping the ref count of a shared_ptr), you won't get the warning.

auto x = std::make_shared<int>(23);
auto foo = [x](){ bar(*x); };

So, short of creating my own [[nodiscard]] wrapper for function objects, are there any extra warning flags I'm missing or static analysis tools that'd pick up this mistake?

Mainly a gcc user, although would be building with clang as well off the same code base.

1 Answers

There's not really anything to warn about in your program. At least, any warnings that might be produced wouldn't fall in the category of -Wunused. That set of warnings is for declarations in a program that have no effect on the behavior of the program, suggesting a programmer mistake. This is generally the case for unused declarations, since declarations by themselves don't usually have any observable side effects.

In your code however, the declaration of foo does have an observable side effect:

auto x = std::make_shared<int>(23);
std::cout << x.use_count();         // prints 1
auto foo = [x](){ bar(*x); };
std::cout << x.use_count()          // prints 2

Here's a demo.

So I don't think any -Wunused warnings would be appropriate for this program.

Related