aboutsummaryrefslogtreecommitdiff
path: root/gcc/cp/call.cc
diff options
context:
space:
mode:
authorMarek Polacek <polacek@redhat.com>2022-11-11 12:01:54 -0500
committerMarek Polacek <polacek@redhat.com>2022-11-14 19:16:35 -0500
commit080b4cf6bd8622c7dff6299f9103184d518ca93f (patch)
tree84aeaeee7582532811422d570f108301f2631db4 /gcc/cp/call.cc
parentaa37a91cab19855ae6b0c6660eff8511b7a81436 (diff)
downloadgcc-080b4cf6bd8622c7dff6299f9103184d518ca93f.zip
gcc-080b4cf6bd8622c7dff6299f9103184d518ca93f.tar.gz
gcc-080b4cf6bd8622c7dff6299f9103184d518ca93f.tar.bz2
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.
Diffstat (limited to 'gcc/cp/call.cc')
-rw-r--r--gcc/cp/call.cc10
1 files changed, 8 insertions, 2 deletions
diff --git a/gcc/cp/call.cc b/gcc/cp/call.cc
index bd3b64a..ef618d5 100644
--- a/gcc/cp/call.cc
+++ b/gcc/cp/call.cc
@@ -13679,8 +13679,14 @@ maybe_warn_dangling_reference (const_tree decl, tree init)
{
if (!warn_dangling_reference)
return;
- if (!(TYPE_REF_OBJ_P (TREE_TYPE (decl))
- || std_pair_ref_ref_p (TREE_TYPE (decl))))
+ tree type = TREE_TYPE (decl);
+ /* Only warn if what we're initializing has type T&& or const T&, or
+ std::pair<const T&, const T&>. (A non-const lvalue reference can't
+ bind to a temporary.) */
+ if (!((TYPE_REF_OBJ_P (type)
+ && (TYPE_REF_IS_RVALUE (type)
+ || CP_TYPE_CONST_P (TREE_TYPE (type))))
+ || std_pair_ref_ref_p (type)))
return;
/* Don't suppress the diagnostic just because the call comes from
a system header. If the DECL is not in a system header, or if