[英]What is the best way to compare uintptr_t and a pointer type?
Is it just the reinterpret_cast? 它只是reinterpret_cast吗?
int *pointer;
uintptr_t value;
value == reinterpret_cast<uintptr_t>(pointer);
Depends on your goal really. 真的取决于你的目标。
[expr.reinterpret.cast] [expr.reinterpret.cast]
4 A pointer can be explicitly converted to any integral type large enough to hold it. 4指针可以显式转换为足以容纳它的任何整数类型。 The mapping function is implementation-defined. 映射函数是实现定义的。 [ Note: It is intended to be unsurprising to those who know the addressing structure of the underlying machine. [注意:对于那些了解底层机器的寻址结构的人来说,这并不奇怪。 — end note ] A value of type
std::nullptr_t
can be converted to an integral type; - 结束注释]std::nullptr_t
类型的值可以转换为整数类型; the conversion has the same meaning and validity as a conversion of(void*)0
to the integral type. 转换与(void*)0
到整数类型的转换具有相同的含义和有效性。5 A value of integral type or enumeration type can be explicitly converted to a pointer. 5可以将整数类型或枚举类型的值显式转换为指针。 A pointer converted to an integer of sufficient size (if any such exists on the implementation) and back to the same pointer type will have its original value; 转换为足够大小的整数(如果实现上存在任何此类)并返回相同指针类型的指针将具有其原始值; mappings between pointers and integers are otherwise implementation-defined. 指针和整数之间的映射在其他方面是实现定义的。
The mapping is implementation defined (obviously). 映射是实现定义的(显然)。 If you wish to check that the value of pointer
was used to initialize value
, then your check is insufficient. 如果您想检查pointer
的值是否用于初始化value
,那么您的检查是不够的。 The above doesn't promise that reinterpret_cast<uintptr_t>(pointer)
will always yield the same integer, even though all sane implementations today do. 上面并没有保证reinterpret_cast<uintptr_t>(pointer)
将始终产生相同的整数,即使今天所有理智的实现都这样做。
I would do the check in reverse, since we have a round trip guarantee: 我会反过来检查,因为我们有往返保证:
reinterpret_cast<int*>(value) == pointer;
But even then, it's a pretty weak guarantee. 但即便如此,这也是一个相当薄弱的保证。 I would not faff about with these conversions too much if I were you. 如果我是你,我不会过多地谈论这些转换。 It may be worth to reconsider your design. 重新考虑您的设计可能是值得的。
If you follow the standard to the letter, you ought to use 如果你遵循标准的字母,你应该使用
value == (uintptr_t)(void*)pointer
or using reinterpret_cast
: 或使用reinterpret_cast
:
value == reinterpret_cast<uintptr_t>(reinterpret_cast<void*>(pointer))
which personally I find less readable. 我个人觉得不太可读。 Naturally the compiler will remove all the "fluff". 编译器自然会删除所有“绒毛”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.