clang has this warning, -Wself-move, which warns about things like this: int a = 1; a = std::move (a); I don't see any reason why code like this would be desirable, so any code that ends up like this would likely be a mistake. It would be nice to point it out. Example output: test.c:6:4: error: explicitly moving variable of type 'int' to itself [-Werror,-Wself-move] a = std::move(a); ~ ^ ~ 1 error generated.
Confirmed.
cc-ing Marek since he wrote a blog post that seems relevant here: https://developers.redhat.com/blog/2019/04/12/understanding-when-not-to-stdmove-in-c/
Ok, this shouldn't be too hard. I guess I could implement it for GCC 10.
Just curious if this code works good with return value optimization like: static inline T conditional_update(T&& src, bool flag) { if (flag) { return T{}; } else { return std::move(src); } } T a; a = conditional_update(a, true); a = conditional_update(a, false); Is it going to produce warning after inlining and propagating constants?..
The warning is taking place in the front end, long before inlining/cprop has run.
(In reply to Marek Polacek from comment #3) > Ok, this shouldn't be too hard. I guess I could implement it for GCC 10. last chance to get it in before stage 1 closes...
(In reply to Eric Gallager from comment #6) > (In reply to Marek Polacek from comment #3) > > Ok, this shouldn't be too hard. I guess I could implement it for GCC 10. > > last chance to get it in before stage 1 closes... I was working on C++20 features which are more important. So this will have to wait until the next stage 1.
Patch posted: https://gcc.gnu.org/pipermail/gcc-patches/2022-August/599503.html
The trunk branch has been updated by Marek Polacek <mpolacek@gcc.gnu.org>: https://gcc.gnu.org/g:0abb78dda084a14b3d955757c6431fff71c263f3 commit r13-2227-g0abb78dda084a14b3d955757c6431fff71c263f3 Author: Marek Polacek <polacek@redhat.com> Date: Mon Aug 8 17:45:28 2022 -0400 c++: Implement -Wself-move warning [PR81159] About 5 years ago we got a request to implement -Wself-move, which warns about useless moves like this: int x; x = std::move (x); This patch implements that warning. PR c++/81159 gcc/c-family/ChangeLog: * c.opt (Wself-move): New option. gcc/cp/ChangeLog: * typeck.cc (maybe_warn_self_move): New. (cp_build_modify_expr): Call maybe_warn_self_move. gcc/ChangeLog: * doc/invoke.texi: Document -Wself-move. gcc/testsuite/ChangeLog: * g++.dg/warn/Wself-move1.C: New test.
Implemented in GCC 13.
Awesome, thanks!
Just ftr: Building GDB with a recent GCC now breaks since GDB is testing -Wself-move in its unittests, but only covers the warning in case of clang. Found by my automated builders. I proposed a patch to fix that.