在 cppref ,我看到一个奇怪的类型特征检查器:std::has_unique_object_representations
根据它的描述,我无法想象任何类型 T
这使得std::has_unique_object_representations<T>::value
是false
.
有没有反例?
最佳答案
理解这个特性的目的需要理解对象“值表示”和它的“对象表示”之间的区别。来自标准:
The object representation of an object of type
T
is the sequence of N unsigned char objects taken up by the object of typeT
, where N equalssizeof(T)
. The value representation of an object is the set of bits that hold the value of typeT
. 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 字节对齐的,所以编译器在 c
和 i
之间插入 3 个字节的填充。由于这三个字节是对象存储的一部分(基于 sizeof(T)
),因此它们是对象的对象表示的一部分。
但这三个字节不是其值表示的一部分。如果您修改了这些字节,它们将不会影响 c
或 i
的值,或有关它们的任何其他内容。
如果您为 T
编写了一个 operator==
重载,则对这些字节的更改不会影响其结果。这也意味着,如果您确实编写了一个 operator==
重载,它不能像这样实现:
bool operator==(const T &lhs, const T &rhs)
{
return std::memcmp(&lhs, &rhs, sizeof(T)) == 0;
}
为什么不呢?因为两个 T
的那些填充字节可以有不同的值,但 c
和 i
的值仍然相同。因此它们具有相同的值表示,因此应被视为等效。
has_unique_object_representations
在 T
的对象表示和它的值表示完全重叠时为真(并且当 T
可简单复制时)。那么,您什么时候会关心这个?
您可以编写一个适用于任何普通可复制类型 T
的通用哈希函数,方法是将其值表示形式读取为字节数组并对其进行哈希处理。好吧,您可以这样做,但前提是该类型没有填充字节。这就是 has_unique_object_representations
告诉您的:对象表示中的所有字节都很重要。
另外,请注意 float
类型不一定具有此值,因为二进制相等性和浮点相等性在 IEEE-754 中不是一回事。因此,包含 float
的类型也不一定是真的。事实上,使用补码有符号整数或带有陷阱表示的有符号整数的实现对于此类类型也不成立。
关于c++ - 什么类型会使 "std::has_unique_object_representations"返回 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42855326/