gpt4 book ai didi

c++ - 比较 uintptr_t 和指针类型的最佳方法是什么?

转载 作者:太空狗 更新时间:2023-10-29 20:33:27 33 4
gpt4 key购买 nike

它只是 reinterpret_cast 吗?

int *pointer;
uintptr_t value;
value == reinterpret_cast<uintptr_t>(pointer);

最佳答案

真的取决于你的目标。

[expr.reinterpret.cast]

4 A pointer can be explicitly converted to any integral type large enough to hold it. 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; the conversion has the same meaning and validity as a conversion of (void*)0 to the integral type.

5 A value of integral type or enumeration type can be explicitly converted to a pointer. 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.

映射是实现定义的(很明显)。如果你想检查 pointer 的值用于初始化 value ,那么你的支票是不够的。以上并不保证 reinterpret_cast<uintptr_t>(pointer)将始终产生相同的整数,即使今天所有理智的实现都是如此。

我会反向检查,因为我们有往返保证:

reinterpret_cast<int*>(value) == pointer;

但即便如此,它的保证也很薄弱。如果我是你,我不会过多地关注这些转换。可能值得重新考虑您的设计。

关于c++ - 比较 uintptr_t 和指针类型的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55159930/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com