什么类型会使 "std::has_unique_object_representations" return 为假?

What type will make "std::has_unique_object_representations" return false?

cppref,我看到一个奇怪的类型特征检查器std::has_unique_object_representations

根据其描述,我无法想象任何使 std::has_unique_object_representations<T>::value 成为 false 的类型 T

有没有反例?

了解此特征的目的需要了解对象 "value representation" 及其 "object representation" 之间的区别。来自标准:

The object representation of an object of type T is the sequence of N unsigned char objects taken up by the object of type T, where N equals sizeof(T). The value representation of an object is the set of bits that hold the value of type T . For trivially copyable types, the value representation is a set of bits in the object representation that determines a value, which is one discrete element of an implementation-defined set of values.

所以,对象表示就是一个对象的总存储量。但是请考虑以下对象:

struct T
{
  char c;
  int i;
};

在许多系统上,sizeof(T) 将是 8。为什么?因为 int 必须是 4 字节对齐的,所以编译器在 ci 之间插入了 3 个字节的填充。由于这三个字节是对象存储的一部分(基于 sizeof(T)),因此它们是对象对象表示的一部分。

但这三个字节不是其值表示的一部分。如果您修改了这些字节,它们将不会影响 ci 的值,或关于它们的任何其他内容。

如果您为 T 编写了 operator== 重载,对这些字节的更改不会影响其结果。这也意味着如果你写了一个 operator== 重载,它 不能 像这样实现:

bool operator==(const T &lhs, const T &rhs)
{
  return std::memcmp(&lhs, &rhs, sizeof(T)) == 0;
}

为什么不呢?因为两个 T 的那些填充字节可以有不同的值,但仍然具有相同的 ci 的值。因此它们具有相同的值表示,因此应该被认为是等价的。

has_unique_object_representationsT 的对象表示及其值表示完全相互重叠时为真(并且当 T 可简单复制时)。那么,你什么时候会关心这个?

您可以编写一个适用于任何普通可复制类型的通用哈希函数 T,方法是将其值表示形式读取为字节数组并对其进行哈希处理。好吧,您 可以 这样做,但前提是该类型没有填充字节。这就是 has_unique_object_representations 告诉你的:对象表示中的所有字节都很重要。

另外,请注意 float 类型不一定具有此值,因为二进制相等性和浮点相等性在 IEEE-754 中不是一回事。所以包含 floats 的类型也不一定是真的。实际上,使用补码有符号整数或带有陷阱表示的有符号整数的实现对于此类类型也不会如此。