c++: Extend -Wdangling-reference for std::minmax
commit7e3ce73849fef8b50efb427ec96f317e88c0e6cf
authorMarek Polacek <polacek@redhat.com>
Thu, 10 Nov 2022 00:35:26 +0000 (9 19:35 -0500)
committerMarek Polacek <polacek@redhat.com>
Thu, 10 Nov 2022 18:17:09 +0000 (10 13:17 -0500)
tree0e4432ebd86e247c6b999b8ead2b122b72da2607
parent740cf7d6ab266cf4249fc5c247187622cb6a2c8f
c++: Extend -Wdangling-reference for std::minmax

This patch extends -Wdangling-reference to also warn for

  auto v = std::minmax(1, 2);

which dangles because this overload of std::minmax returns
a std::pair<const int&, const int&> where the two references are
bound to the temporaries created for the arguments of std::minmax.
This is a common footgun, also described at
<https://en.cppreference.com/w/cpp/algorithm/minmax> in Notes.

It works by extending do_warn_dangling_reference to also warn when the
function returns a std::pair<const T&, const T&>.  std_pair_ref_ref_p
is a new helper to check that.

gcc/cp/ChangeLog:

* call.cc (std_pair_ref_ref_p): New.
(do_warn_dangling_reference): Also warn when the function returns
std::pair<const T&, const T&>.  Recurse into TARGET_EXPR_INITIAL.
(maybe_warn_dangling_reference): Don't return early if we're
initializing a std_pair_ref_ref_p.

gcc/ChangeLog:

* doc/gcc/gcc-command-options/options-controlling-c++-dialect.rst:
Extend the description of -Wdangling-reference.

gcc/testsuite/ChangeLog:

* g++.dg/warn/Wdangling-reference6.C: New test.
gcc/cp/call.cc
gcc/doc/gcc/gcc-command-options/options-controlling-c++-dialect.rst
gcc/testsuite/g++.dg/warn/Wdangling-reference6.C [new file with mode: 0644]