A return of a temporary from a lambda assigned to `std::function<>` does not cause a warning, unlike a regular function. Would be useful if it trapped, but it may be too far down the deduction path. <code> #include <iostream> #include <functional> struct S { int s{}; }; using F = std::function<S const& ()>; S const& fn() { return S{}; // Warning: returning ref to temporary } int main() { F f = [](){ return S{}; }; // No warning std::cout << f().s << std::endl; // Ouch } </code> g++-11 -W -Wall -std=c++20 -O2 -pedantic-errors test.cpp --save-temps g++-11 --version g++-11 (GCC) 11.2.1 20211105
That is because the lambda itself returns a S and not a const reference. You do get a warning with -Wsystem-headers inside invoke. With: []() -> S const& { return S{}; }; You do get the correct warning. Also this has nothing to do with lambdas really but really std::function as shown by: struct S { int s{}; }; using F = std::function<S const& ()>; auto fn() { return S{}; } int main() { F f = fn; // No warning __builtin_printf("%d.\n", f().s); } ---- CUT ---- The above code is the same as the lambda case really.
This is a dup of bug 70692. *** This bug has been marked as a duplicate of bug 70692 ***