Bug 103543 - Potential compiler warning for return of temporary with std::function<const T&()> converting from T(*)()
Summary: Potential compiler warning for return of temporary with std::function<const T...
Status: RESOLVED DUPLICATE of bug 70692
Alias: None
Product: gcc
Classification: Unclassified
Component: c++ (show other bugs)
Version: 11.2.1
: P3 normal
Target Milestone: ---
Assignee: Not yet assigned to anyone
URL:
Keywords: diagnostic
Depends on:
Blocks:
 
Reported: 2021-12-03 16:10 UTC by Richard Hazlewood
Modified: 2021-12-03 19:45 UTC (History)
0 users

See Also:
Host:
Target:
Build:
Known to work:
Known to fail:
Last reconfirmed:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Richard Hazlewood 2021-12-03 16:10:58 UTC
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
Comment 1 Drea Pinski 2021-12-03 19:44:05 UTC
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.
Comment 2 Drea Pinski 2021-12-03 19:45:10 UTC
This is a dup of bug 70692.

*** This bug has been marked as a duplicate of bug 70692 ***