隐式转换警告 int 到 int-lookalike

Implicit conversion warning int to int-lookalike

我的编译器让我对很多隐式转换感到温暖:

有些我确实理解,比如

implicit conversion changes signedness: 'int' to 'std::vector::size_type' (aka 'unsigned long')` 

当我做 myvector.resize(myInt) .

其他比较晦涩的,比如

implicit conversion loses integer precision: 'std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::size_type' (aka 'unsigned long') to 'int'

当我myInt=myString.size(),或

implicit conversion changes signedness: 'int' to 'std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::size_type' (aka 'unsigned long')

当我打电话给 myString[myInt]

在所有情况下,我确实理解为什么会收到这些消息(int-uint 等),但是它们在程序中的使用是明确的。如果我不寻找更改我的变量类型来删除这些警告,我会有什么风险?我以前的编译器没有警告我任何东西,所以当我换电脑时突然有几十个警告。

I all cases, I do understand why I get these message (int-uint, etc), however their use is non-ambiguous in the program. What do I risk if I do not hunt change the type of my variables to delete these warning?

不是歧义。如果将有符号值转换为无符号类型,可能会得到奇怪的结果:

long i = -2147483645;        // for example

std::vector<int> vec{0, 1, 2, 3, 4};
std::cout << vec[i] << "\n"; // undefined behavior, not always caught

此处,假设是 32 位系统,i 在传递给 operator[] 之前被转换为 2147483651,导致未定义的行为。

如果您真的确定转换是无害的,您可以static_cast:

static_cast<std::vector<int>::size_type>(i)

My previous compiler didn't warn me of anything, so when I changed my PC I suddenly had dozens of warning.

始终打开警告。至少-Wall。在编写库时,我倾向于确保我的代码即使使用 -Wextra 也能干净地编译。它们可以帮助您捕获很多错误。

stl 的 size_type 归结为您的编译器的 unsigned long。将其分配给 int.

等签名类型时会发出 implicit conversion changes signedness 警告

此外 long 的宽度取决于 cpu 架构,即它在 x86 上是 32 位,但在 x64 上是 64 位,而 int 被定义为 32 位宽度.这会发出 implicit conversion loses integer precision 警告。

My previous compiler didn't warn me of anything, so when I changed my PC I suddenly had dozens of warning

可能是您的新 PC 上的警告级别更高。检查 -W3 (Windows)、-Wall-Wextra (GCC) 的编译器选项。

What do I risk if I do not hunt change the type of my variables to delete these warning?

如果 stl 容器的大小不适合 int,这至少是一种糟糕的风格并且会导致未定义的行为。