简体   繁体   English

不要使用 static 进行算术转换(cpp-core-guidelines)

[英]Don't use static cast for arithmetic conversions (cpp-core-guidelines)

msvc's code analyzer for the cpp core guidelines tells me msvc 的 cpp 核心指南代码分析器告诉我

Warning C26472 Don't use a static_cast for arithmetic conversions.警告 C26472 不要使用 static_cast 进行算术转换。 Use brace initialization, gsl::narrow_cast or gsl::narrow (type.1).使用大括号初始化、gsl::narrow_cast 或 gsl::narrow (type.1)。

for this snippet对于这个片段

static_cast<IntType>(static_cast<unsigned long long>(hexValue(digit)) << (digitIdx * 4));

Why shouldn't I use static_cast here?为什么我不应该在这里使用 static_cast ?

Also, with brace init this would look like this此外,使用大括号初始化,这看起来像这样

IntType{unsigned long long{hexValue(digit)} << (digitIdx * 4)};

which doesn't look any better imo.这看起来并没有更好的海事组织。 This looks more like a function style cast than anything else.这看起来更像是 function 风格的演员。

I cannot use gsl and I think gsl::narrow is a wrapper around static_cast itself, so is this purely a readability issue here?我不能使用 gsl 并且我认为gsl::narrowstatic_cast本身的包装器,所以这纯粹是一个可读性问题吗?

so is this purely a readability issue here?那么这纯粹是一个可读性问题吗?

Nope.没有。 Brace initialization prohibits narrowing conversions, and will cause a diagnostic.大括号初始化禁止缩小转换,并会导致诊断。 The guideline's purpose is to help protect code from unintended narrowing.该指南的目的是帮助保护代码免受意外缩小。 A static_cast will allow a narrowing conversion through silently. static_cast将允许通过静默进行缩小转换。

You seem to be dealing in integers, so short of using an extended integer type that is larger than unsigned long long , you'll probably not hit any narrowing.您似乎在处理整数,因此没有使用大于unsigned long long的扩展 integer 类型,您可能不会遇到任何缩小。

But the guideline is there for the general case, and it's better to write code consistently, even when there is no actual risk.但是指导方针是针对一般情况的,最好是一致地编写代码,即使没有实际风险。

Here is a link to Microsoft documentation:以下是 Microsoft 文档的链接:

[https://docs.microsoft.com/en-us/cpp/code-quality/c26472?view=vs-2019][1] [https://docs.microsoft.com/en-us/cpp/code-quality/c26472?view=vs-2019][1]

  • gsl::narrow ensures lossless conversion and causes run-time crash if it is not possible. gsl::narrow 确保无损转换并在不可能的情况下导致运行时崩溃。
  • gsl::narrow_cast clearly states that conversion can lose data and it is acceptable. gsl::narrow_cast 明确指出转换可能会丢失数据,这是可以接受的。

static_cast doesn't perform these checks, so it is safer to explicitly state your intentions. static_cast不执行这些检查,因此明确 state 您的意图更安全。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM