为什么在添加 Short 时会出现从 int 到 Short 的缩小转换警告?(C++)

And*_*s C 3 c++ types type-conversion narrowing

对于以下数组,我有一个与此类似的代码:

long int N = 424242424242; //random number
short int* spins = new short int spins[N];
std::fill(spins, spins+N, 1);

Run Code Online (Sandbox Code Playgroud)

现在假设由于某种原因我想将该数组的几个元素添加到一个名为 nn_sum 的短整型中:

short int nn_sum = spins[0] + spins[1];
Run Code Online (Sandbox Code Playgroud)

但是,当我在 CLion IDE 上执行此操作时,Clang-Tidy 将其标记为黄色并告诉我:

Clang-Tidy: Narrowing conversion from 'int' to signed type 'short' is implementation-defined
Run Code Online (Sandbox Code Playgroud)

为什么会发生这种情况?为什么会出现缩小呢?C++ 在添加短整型时是否会将它们转换为整数?如果是这样,为什么?我能做些什么来让它更好地工作吗?也许甚至完全放弃短裤?

请记住,我在应用程序的计算密集型部分中有这样的代码因此我希望使其尽可能高效。任何其他建议也将不胜感激。

Mar*_*ila 5

发生这种情况是因为整数提升。两个值相加的结果short不是short,而是int

您可以通过 cppinsights.io 检查这一点:

short a = 1;
short b = 2;
auto c = a + b;  // c is int
Run Code Online (Sandbox Code Playgroud)

演示: https: //cppinsights.io/s/68e27bd7