Joh*_*qua 3 c++ gcc-warning implicit-conversion
I decided to test compile a project with -Wsign-conversion enabled, to see what warnings would come up, and came across something that doesn't seem right, where gcc behaves differently than clang. Can someone please tell me which is correct?
I have a function that takes a size_t param:
void func(size_t) {}
Run Code Online (Sandbox Code Playgroud)
some other struct
struct Test {};
Run Code Online (Sandbox Code Playgroud)
and calling code
int i = some_initialiser();
func(sizeof(Test) + static_cast<size_t>(i));
Run Code Online (Sandbox Code Playgroud)
So from my understanding, sizeof returns size_t, and arithmetic between two variables of type size_t should return a size_t, so there shouldn't be any conversion here other than my static_cast, but gcc gives me the warning
warning: conversion to ‘long unsigned int’ from ‘int’ may change the sign of the result [-Wsign-conversion]
Run Code Online (Sandbox Code Playgroud)
Clang doesn't warn here, but does warn if I remove the static_cast in the function call, as expected.
这是gcc中的已知错误,现已修复,但尚未发布。
该警告是有效的(编译器可以警告他们喜欢的任何东西),但是gcc的行为与它自己的文档相矛盾。有针对此问题的现有错误报告(请参见下文)。
这是一个更简单的测试案例,说明了这个问题:
#include <cstddef>
int main() {
int i = 42;
size_t s0 = sizeof (int) + (size_t)i;
size_t s1 = sizeof (int) + static_cast<size_t>(i);
}
Run Code Online (Sandbox Code Playgroud)
当我使用gcc 9.1.0在系统上编译它时,我得到:
$ g++ -Wsign-conversion -c c.cpp
c.cpp: In function ‘int main()’:
c.cpp:4:32: warning: conversion to ‘long unsigned int’ from ‘int’ may change the sign of the result [-Wsign-conversion]
4 | size_t s0 = sizeof (int) + (size_t)i;
| ^~~~~~~~~
c.cpp:5:32: warning: conversion to ‘long unsigned int’ from ‘int’ may change the sign of the result [-Wsign-conversion]
5 | size_t s1 = sizeof (int) + static_cast<size_t>(i);
| ^~~~~~~~~~~~~~~~~~~~~~
$
Run Code Online (Sandbox Code Playgroud)
请注意,对于C样式强制转换和都将发生警告static_cast。
这是真的,转换可能改变结果的符号(负转换int,以size_t产生肯定的结果),但对gcc的文件-Wsign-conversion说:
'-Wsign-conversion'
Warn for implicit conversions that may change the sign of an
integer value, like assigning a signed integer expression to an
unsigned integer variable. An explicit cast silences the warning.
In C, this option is enabled also by '-Wconversion'.
Run Code Online (Sandbox Code Playgroud)
在这种情况下,显式强制转换不会使警告消失。
已经报告了该错误:
错误87519--Wsign-conversion -Wconversion显式强制转换无法使警告静音
我已经添加了测试用例以及指向该问题和错误报告的答案的链接。
一个新的评论从马立克Polacek的在错误报告:
在中继上已修复,稍后将反向移植到9.3。
该修复程序61e52125c935279af11b10d27060a96bff7477a4在2019年8月8日提交的gcc git repo中提交。