3

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)
Ali
  • 366
  • 4
  • 11
  • The linked target is identical apart from the fact that you've used a lambda, instead of an `int`/`double`, so I think it's sufficiently close to be marked as a duplicate. – cigien Oct 20 '21 at 16:10

1 Answers1

4

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
Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • Oh dear, I don't know what (non)trivial constructor is. I need to study them. – Ali Oct 20 '21 at 16:13
  • 1
    trivial destructor (typo, not constructor :) )link added. Basically, trivial destructor is known to be noop (by compiler). – Jarod42 Oct 20 '21 at 16:19
  • So, I have two questions. 1. Why compiler does not warn for an unused RAII object? 2. What does it mean for a lambda function to have a destructor? – Ali Oct 20 '21 at 16:53
  • 1
    As RAII object might have a scope meaning: you don't want warning for [`std::lock_guard`](https://en.cppreference.com/w/cpp/thread/lock_guard). The real usage is just to define the variable and not use afterward. – Jarod42 Oct 20 '21 at 16:54
  • 1
    (non-capture) `lambda` has trivial destructor, std::function is a type-erasure type, which has a provided destructor (to "deallocate" the erased type). – Jarod42 Oct 20 '21 at 17:13