使用 nullptr 会产生编译器错误吗?

发布于 2024-10-14 20:07:18 字数 135 浏览 10 评论 0原文

这段代码在使用 Visual C++ 2010 进行编译时没有警告(并且运行时崩溃)是否有充分的理由:

int a = *((int*)nullptr);

静态分析应该断定它将崩溃,对吗?

Is there a good reason why this code compiles without warning (and crashes when run) with Visual C++ 2010:

int a = *((int*)nullptr);

Static analysis should conclude that it will crash, right?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

稚气少女 2024-10-21 20:07:18

使用 nullptr 会产生编译器错误吗?

不会。

取消引用空指针会导致未定义的行为,但不需要进行诊断。

静态分析应该得出结论,它会崩溃,对吧?

可能会。没必要。如果发出警告当然是件好事。专用的静态分析工具(例如 Klocwork)可能会发出警告。

Should this use of nullptr produce a compiler error?

No.

Dereferencing a null pointer results in undefined behavior, but no diagnostic is required.

Static analysis should conclude that it will crash, right?

It might. It doesn't have to. It would certainly be nice if a warning was issued. A dedicated static analysis tool (Klocwork, for example) would probably issue a warning.

半边脸i 2024-10-21 20:07:18

是的,静态分析表明它总是会崩溃。但是,这需要编译器实际执行此静态分析。大多数编译器不会这样做(至少我不知道)。

所以问题是:为什么 C/C++ 编译器不做更多的静态类型检查。

编译器不这样做的原因主要是:传统,以及使编译器尽可能简单的哲学。

C(以及较小程度上的 C++)是在计算能力相当昂贵且易于编写编译器非常重要的环境中创建的(因为有许多不同的硬件架构)。

由于静态类型检查分析会使编译器更难编写,并且编译速度更慢,因此当时并不认为这是一个优先事项。因此大多数编译器没有它。

其他语言(例如,Java)做出了不同的权衡,因此在 Java 中,许多在 C 中允许的事情是非法的(例如,无法访问的代码是 Java 中的编译时错误;在 C 中,大多数编译器甚至不会发出警告)。这确实可以归结为哲学。

顺便说一句,请注意,如果您愿意,您可以在 C 中进行静态类型检查 - 有多种工具可用,例如 lint(古老),或参见 有哪些开源 C++ 静态分析工具可用? .

Yes, static analysis would show this to always crash. However, this would require the compiler to actually perform this static analysis. Most compilers do not do this (at least none I know of).

So the question is: Why don't C/C++ compilers do more static type checking.

The reason the compiler does not do this is mostly: tradition, and a philosophy of making the compiler as simple as possible.

C (and to a lesser degree C++) were created in an environment where computing power was fairly expensive, and where ease of writing a compiler was important (because there were many different HW architectures).

Since static typechecking analysis will both make a compiler harder to write, and make it compile more slowly, it was not felt at the time to be a priority. Thus most compilers don't have it.

Other languages (e.g.) Java make different tradeoffs, and thus in Java many things are illegal that are allowed in C (e.g. unreachable code is a compile-time error in Java; in C most compilers don't even warn). This really boils down to philosophy.

BTW, note that you can get static typechecking in C if you want it - there are several tools available, e.g. lint (ancient), or see What open source C++ static analysis tools are available? .

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文