From b3c98d6a59a6dcd5b0b52bd5676b586ef4fe785f Mon Sep 17 00:00:00 2001 From: Marek Polacek Date: Tue, 18 Oct 2022 12:20:14 -0400 Subject: c++: Mitigate -Wuseless-cast with classes [PR85043] -Wuseless-cast (not part of -Wall/-Wextra) warns here: struct S { }; void g (S&&); void f (S&& arg) { g (S(arg)); // warning: useless cast to type 'struct S' } which is wrong: the code will not compile without the cast because "arg" is an lvalue which cannot bind to S&&. This patch disables the warning when an object that isn't a prvalue is cast to a non-reference type. Therefore we still warn about the useless cast in "X(X{})". PR c++/85043 gcc/cp/ChangeLog: * typeck.cc (maybe_warn_about_useless_cast): Don't warn when a glvalue is cast to a non-reference type. gcc/ChangeLog: * doc/invoke.texi: Update documentation of -Wuseless-cast. gcc/testsuite/ChangeLog: * g++.dg/warn/Wuseless-cast.C: Remove dg-warning. * g++.dg/warn/Wuseless-cast3.C: New test. --- gcc/doc/invoke.texi | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) (limited to 'gcc/doc') diff --git a/gcc/doc/invoke.texi b/gcc/doc/invoke.texi index c176e2d..cd4d3c1 100644 --- a/gcc/doc/invoke.texi +++ b/gcc/doc/invoke.texi @@ -4551,7 +4551,18 @@ pointers after reallocation. @item -Wuseless-cast @r{(C++ and Objective-C++ only)} @opindex Wuseless-cast @opindex Wno-useless-cast -Warn when an expression is casted to its own type. +Warn when an expression is cast to its own type. This warning does not +occur when a class object is converted to a non-reference type as that +is a way to create a temporary: + +@smallexample +struct S @{ @}; +void g (S&&); +void f (S&& arg) +@{ + g (S(arg)); // make arg prvalue so that it can bind to S&& +@} +@end smallexample @item -Wno-conversion-null @r{(C++ and Objective-C++ only)} @opindex Wconversion-null -- cgit v1.1