https://gcc.gnu.org/bugzilla/show_bug.cgi?id=100405
Jonathan Wakely <redi at gcc dot gnu.org> changed:
What |Removed |Added
----------------------------------------------------------------------------
Summary|missing return assignment |Add implicit 'return
| |*this;' in assignment
| |operators
Resolution|INVALID |---
Severity|normal |enhancement
See Also| |https://gcc.gnu.org/bugzill
| |a/show_bug.cgi?id=85523
Last reconfirmed| |2021-05-03
Ever confirmed|0 |1
Status|RESOLVED |NEW
--- Comment #2 from Jonathan Wakely <redi at gcc dot gnu.org> ---
It would be nice if G++ would Do The Right Thing here:
struct T
{
T& operator=(const T& t)
{
i = t.i;
/* forgot to write return *this; */
}
int i = 0;
};
If the user forgets to write 'return *this;' in an assignment operator the
results can be quite unpleasant (after optimization).
Similar to the implicit 'return 0;' in main it would be nice to add an implicit
return *this to assignment operators. It could be done in cases where
-Wreturn-type warns (e.g. there isn't a throw or a call to a noreturn function
before the end of the function) and if the return type is decltype(*this).
G++ does give a -Wreturn-type warning for the example above (and since gcc 9 it
adds a fix-it hint, thanks to PR 85523) but for a template it doesn't warn
until it's instantiated:
template<typename>
struct T
{
T& operator=(const T& t)
{
i = t.i;
/* forgot to write return *this; */
}
int i = 0;
};
This compiles without a warning (which is PR 48586).