c++ - std::byte 的用例

标签 c++ c++17

<分区>

最近将 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.

如上文所述,这确保了额外的类型安全。

关于c++ - std::byte 的用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48355242/

相关文章:

android - iOS/Android SDK 中的 C++17 支持

c++ - 递归查找二叉树中的最小数

c++ - Lambda 函数参数 + 推导改进

c++ - 使用 ITK 操作 Nifti 图像

c++ - 字符串在函数中的作用域

c++ - 为什么这个正则表达式在 STL 世界中是错误的?

c++ - 是 new(&*p) double;无操作。因此,uninitialized_default_construct 是否也变为无操作?

C++17 使用模板参数推导指南继承 lambda 集

c++ - 负数的按位运算会导致ub吗?

c++ - 生产者-消费者队列- std::queue 还是用户编写的链表?