c++: Extend -Wpessimizing-move for class prvalues [PR106276]
commitae3459cd5956fcd29e8aa5408efb707cb7d9b14f
authorMarek Polacek <polacek@redhat.com>
Fri, 22 Jul 2022 22:10:30 +0000 (22 18:10 -0400)
committerMarek Polacek <polacek@redhat.com>
Mon, 15 Aug 2022 13:51:04 +0000 (15 09:51 -0400)
tree5167eb50e7881a8d5792969aaa91aedc9e4ec3d1
parente236d671d460dd47262accdea2e9d1d80820ae88
c++: Extend -Wpessimizing-move for class prvalues [PR106276]

We already have a warning that warns about pessimizing std::move
in a return statement, when it prevents the NRVO:

  T fn()
  {
    T t;
    return std::move (t); // warning \o/
  }

However, the warning doesn't warn when what we are returning is a class
prvalue, that is, when std::move prevents the RVO:

  T fn()
  {
    T t;
    return std::move (T{}); // no warning :-(
  }

This came up recently in GCC:
<https://gcc.gnu.org/pipermail/gcc-patches/2022-July/598177.html>.

This patch fixes that.  I would like to extend the warning further, so
that it warns in more contexts, e.g.:

  T t = std::move(T());

or

  void foo (T);
  foo (std::move(T()));

PR c++/106276

gcc/cp/ChangeLog:

* typeck.cc (can_do_rvo_p): New.
(maybe_warn_pessimizing_move): Warn when moving a temporary object
in a return statement prevents copy elision.

gcc/testsuite/ChangeLog:

* g++.dg/cpp0x/Wpessimizing-move7.C: New test.
gcc/cp/typeck.cc
gcc/testsuite/g++.dg/cpp0x/Wpessimizing-move7.C [new file with mode: 0644]