c++: -Wdangling-reference with reference wrapper [PR107532]
commit80f0052b3924569af904d1bab0858fe985f33a94
authorMarek Polacek <polacek@redhat.com>
Tue, 17 Jan 2023 22:34:58 +0000 (17 17:34 -0500)
committerMarek Polacek <polacek@redhat.com>
Tue, 7 Mar 2023 16:05:30 +0000 (7 11:05 -0500)
treeeb1b517d17759ab683ec3b2f12676011eac85dd3
parentb2b841fa25513a87fcb6e8195c2ad3ea354426d4
c++: -Wdangling-reference with reference wrapper [PR107532]

Here, -Wdangling-reference triggers where it probably shouldn't, causing
some grief.  The code in question uses a reference wrapper with a member
function returning a reference to a subobject of a non-temporary object:

  const Plane & meta = fm.planes().inner();

I've tried a few approaches, e.g., checking that the member function's
return type is the same as the type of the enclosing class (which is
the case for member functions returning *this), but that then breaks
Wdangling-reference4.C with std::optional<std::string>.

This patch adjusts do_warn_dangling_reference so that we look through
reference wrapper classes (meaning, has a reference member and a
constructor taking the same reference type, or is std::reference_wrapper
or std::ranges::ref_view) and don't warn for them, supposing that the
member function returns a reference to a non-temporary object.

PR c++/107532

gcc/cp/ChangeLog:

* call.cc (reference_like_class_p): New.
(do_warn_dangling_reference): Add new bool parameter.  See through
reference_like_class_p.

gcc/testsuite/ChangeLog:

* g++.dg/warn/Wdangling-reference8.C: New test.
* g++.dg/warn/Wdangling-reference9.C: New test.
gcc/cp/call.cc
gcc/testsuite/g++.dg/warn/Wdangling-reference8.C [new file with mode: 0644]
gcc/testsuite/g++.dg/warn/Wdangling-reference9.C [new file with mode: 0644]