gnu /
gcc /
080b4cf6bd8622c7dff6299f9103184d518ca93f c++: Disable -Wdangling-reference when initing T&
Non-const lvalue references can't bind to a temporary, so the
warning should not be emitted if we're initializing something of that
type. I'm not disabling the warning when the function itself returns
a non-const lvalue reference, that would regress at least
const int &r = std::any_cast<int&>(std::any());
in Wdangling-reference2.C where the any_cast returns an int&.
Unfortunately, this patch means we'll stop diagnosing
int& fn(int&& x) { return static_cast<int&>(x); }
void test ()
{
int &r = fn(4);
}
where there's a genuine dangling reference. OTOH, the patch
should suppress false positives with iterators, like:
auto &candidate = *candidates.begin ();
and arguably that's more important than detecting some relatively
obscure cases. It's probably not worth it making the warning more
complicated by, for instance, not warning when a fn returns 'int&'
but takes 'const int&' (because then it can't return its argument).
gcc/cp/ChangeLog:
* call.cc (maybe_warn_dangling_reference): Don't warn when initializing
a non-const lvalue reference.
gcc/testsuite/ChangeLog:
* g++.dg/cpp23/elision4.C: Remove dg-warning.
* g++.dg/warn/Wdangling-reference1.C: Turn dg-warning into dg-bogus.
* g++.dg/warn/Wdangling-reference7.C: New test.
4 files changed