镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

Design note: Unsafe code

Herb Sutter edited this page Oct 7, 2024 · 5 revisions

Q: Should we be able to implement very-low-level facilities in Cpp2? If so will it have unsafe blocks/functions?

A: Yes, I intend that we can write full programs in Cpp2 syntax only. No, I'm not a fan of "unsafe" as a monolithic hammer, I want to be able to declare my intent of which rules I want to break and suspend only those.

I don’t like monolithic "unsafe" that turns off checking for all rules, because it doesn't express the programmer's intent. The programmer usually doesn’t want to disable all rules, just one specific one. With a monolithic "unsafe," if the same statement accidentally violates a second unrelated rule than we lose diagnosing that unintended bug.

For example, if I want to just do an explicit unsafe cast, in today's syntax something like this:

reinterpret_cast<PodType*>(&myspan[idx])

In Cpp2, if I need to express "trust me, let me reinterpret-cast already!", I can write unchecked_cast:

unchecked_cast<*PodType>(myspan[idx]&)

Note that just because I wanted to opt into doing the cast doesn't mean I want to turn off other safety, such as bounds checking on [idx] operation... that is still bounds-checked. I wanted to tactically remove checking for just that one operation.

Clone this wiki locally