-Wunused-but-set-variable is emitted when I use 'auto' and not when I use the corresponding type instead of 'auto'

Viewed 285

Please consider the following:

#include <functional>

int main() {
    std::function<int(int)> f_sq = [](int i) -> int { return i *= i; }; // No warning
    auto f_sub = [](int a, int b) -> int { return a - b; };             // -Wunused-but-set-variable

    return 0;
}

Why compiler warns when the auto keyword is used, and/or, in the contrary, why it doesn't when auto is not used?


  • clang version 12.0.1
  • gcc (GCC) 11.1.0
  • Target: x86_64-pc-linux-gnu (artixlinux)
1 Answers

std::function<int(int)> has a non trivial destructor, so might be a RAII object.

Your lambda (remember, lambda is NOT a std::function) has trivial destructor, so it is not a RAII object, so it is really unused.

You might minimize your example with simpler types to avoid confusion lambda/std::function:

std::vector<int> v = {4, 8, 15, 16, 23, 42}; // No warnings
int n = 42;                                  // -Wunused-but-set-variable
Related