c++ - 一个普通的 `char` 可能有陷阱值吗?

标签 c++ c++11 language-lawyer c++14

README

A "trap value", or "trap representation" for type T, is a bit combination (of the underlying storage) that yields an invalid value of T. Trying to interpret the representation of an invalid value will cause undefined behavior.


让战斗开始吧..

另一个 question已经开始了关于 char 的激烈讨论,以及具有 trap representations 的实现的可能性为它。

问题:

  • char 可能有陷阱值吗?

前面讨论中提到的引语:

这些部分是之前论证中引用最多的部分,它们是否相互矛盾?

3.9.1p1 Fundamental types [basic.fundamental]

It is implementation-defined whether a char can hold negative values. Characters can be explicitly declared signed or unsigned.

A char, a signed char, and an unsigned char occupy the same amount of storage and have the same alignment requirements (3.11); that is, they have the same object representation. For character types, all bits of the object representation participate in the value representation.

For unsigned character types, all possible bit patterns of the value representation represent numbers. These requirements do not hold for other types.

In any particular implementation, a plain char object can take on either the same values as a signed char or an unsigned char; which one is implementation-defined.

3.9p2 Types [basic.types]

For any object (other than a base-class subobject) of trivially copyable type T, whether or not the object holds a valid value of type T, the underlying bytes (1.7) making up the object can be copied into an array of char or unsigned char.

If the content of the array of char or unsigned char is copied back into the object, the object shall subsequently hold its original value.

最佳答案

标准告诉我们必须有:

  • char、signed char、unsigned char,大小都一样
  • sizeof(char) 为 1
  • char 至少有 8 位
  • 每一个比特组合都是有意义且有效的
  • char 数组已打包(如果是,则行为是)。

没有太多的回旋余地。

尽管如此,还是有建议在某些类型的操作期间,例如加载未初始化的内存或转换为陷阱。

是的,我认为一个实现可能有一个陷阱表示,其中陷阱值可能由于某种未定义或未指定的行为而出现,包括评估涉及未指定/未初始化值的表达式。导致陷阱值的实际位模式对实现来说是不可见的。

这样的 CPU 可能有 9 位字节,其中只有 8 位对编译器和运行时可见,第 9 位用于检测未初始化的内存,如果被(非特权)指令加载,将触发陷阱。

关于c++ - 一个普通的 `char` 可能有陷阱值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24034296/

相关文章:

c++ - 奇怪的 GCC 行为

c++ - 我在 C++ 草稿 GitHub 中找不到问题或拉取请求,支持 [basic.start.static]/2 中的以下更改

c++ - 函数返回值是否是自动对象并因此保证被破坏?

c++ - Vulkan-hpp 正在将非标准布局类重新解释为另一个类。这是合法的吗?

c++ - QT:QActionGroup 添加到 QMenu 后,其成员的父对象是谁?

c++ - 使用 boost bind 时对非静态成员函数的使用无效 - C++

C++ 重载函数作为模板参数

php - 在 MacOSX 10.10 (yosemite) 上编译 php5.5.18 时出错

c++ - 调用 std::map::find 时出现 "map/set iterators incompatible"

c++ - 如何将基类仅链接到其顶级模板化父级?