最近将 std::byte
添加到 C++17 让我想知道为什么这个类型甚至被添加到标准中。即使看完了the cppreference reference它的用例对我来说似乎不清楚。
我能想到的唯一用例是它更清楚地表达了意图,因为 std::byte
应该只被视为位的集合而不是字符类型,例如 char
我们之前用于这两个目的。
意思是:
这个:
std::vector<std::byte> memory;
比这更清楚:
std::vector<char> memory;
这是唯一的用例和将其添加到标准的原因,还是我在这里遗漏了一个重点?
The only use case I can come up with is that it more clearly expresses intent
我认为这是原因之一。 This paper解释了 std::byte
背后的动机,并将其用法与 char 的用法进行了比较:
Motivation and Scope
Many programs require byte-oriented access to
memory. Today, such programs must use either the char, signed char, or
unsigned char types for this purpose. However, these types perform a
“triple duty”. Not only are they used for byte addressing, but also as
arithmetic types, and as character types. This multiplicity of roles
opens the door for programmer error – such as accidentally performing
arithmetic on memory that should be treated as a byte value – and
confusion for both programmers and tools. Having a distinct byte type
improves type-safety, by distinguishing byte-oriented access to memory
from accessing memory as a character or integral value. It improves
readability.
Having the type would also make the intent of code
clearer to readers (as well as tooling for understanding and
transforming programs). It increases type-safety by removing
ambiguities in expression of programmer’s intent, thereby increasing
the accuracy of analysis tools.
另一个原因是std::byte在可以对此类型执行的操作方面受到限制:
Like char and unsigned char, it can be used to access raw memory
occupied by other objects (object representation), but unlike those
types, it is not a character type and is not an arithmetic type. A
byte is only a collection of bits, and only bitwise logic operators
are defined for it.
如上文所述,这确保了额外的类型安全。